<?php
$db = new Database();
$auth = Auth::getAuth('current_user');
$userCompany = new userQueries();
$company = $userCompany->getCompany($auth['company_id']);
$upload = new upload();

$personDoc = new Person($db, $auth['id']);
$userDepartmentName = $personDoc->department->name;

// $YEAH_FORMULA = new Formula("@Department[Requestor] + @TrackNo + @DEPARTMENTFIELD");
// print_r($YEAH_FORMULA->setSourceForm("DYNAMIC_TABLE_TESTING","*",array("TESTING3DIGIT"=>"JC000") ) );
// print_r($YEAH_FORMULA->getProccessedFormula());
// $YEAH_FORMULA = new Formula("@Lookup('DYNAMIC_TABLE_TESTING' , 'TrackNo')");
// print_r($YEAH_FORMULA->getProccessedFormula());
// $YEAH_FORMULA = new Formula("@Concat('DYNAMIC_TABLE_TESTING' , 'TrackNo','biscuites')");
// print_r($YEAH_FORMULA->getProccessedFormula());
// print_r(eval($YEAH_FORMULA->getProccessedFormula()));

if ($_GET['view_type'] == "preview") {
    $formWidth = $_GET['formWidth'];
    $formHeight = $_GET['formHeight'];
    $form_container = "style='margin: 0px auto;width:" . $formWidth . "px;'";
    $form_size = "style=' background-color: #fff;height:" . $formHeight . "px;'";
} elseif ($_GET['view_type'] == "request" || $_GET['view_type'] == "report") {
    // Get Workspace Information
    $getID = $_GET['formID'];
    $requestID = $_GET['requestID'];

    $str = "SELECT WS.*, WFO.workflow_id, WFO.buttonStatus,WFO.fieldEnabled, WFO.fieldRequired, WFO.fieldHiddenValue FROM tb_workspace WS 
                           LEFT JOIN tbworkflow WF
                            ON WS.Id = WF.form_id 
                           LEFT JOIN tbworkflow_objects WFO
                            ON WFO.workflow_id = WF.id 
                            WHERE WS.id={$db->escape($getID)} AND WFO.type_rel = '1'  AND WF.Is_Active = '1'";
    $form = $db->query($str, "row");


    $form_json = json_decode($form['form_json'], true);

    $form_container = "style='margin: 0px auto;width:" . $form_json['WorkspaceWidth'] . "px;'";
    $form_size = "style=' background-color: #fff;height:" . $form_json['WorkspaceHeight'] . "px;'";

    $fieldEnabled = $form['fieldEnabled'];
    $fieldRequired = $form['fieldRequired'];
    $fieldHiddenValues = $form['fieldHiddenValue'];
} elseif ($_GET['view_type'] == "update") {
    // Get Workspace Information
    $getID = $_GET['ID'];
    $requestID = $_GET['requestID'];

    $str = "SELECT WS.*, WFO.workflow_id, WFO.buttonStatus,WFO.fieldEnabled, WFO.fieldRequired, WFO.fieldHiddenValue FROM tb_generate WS 
                           LEFT JOIN tbworkflow WF
                            ON WS.form_id = WF.form_id 
                           LEFT JOIN tbworkflow_objects WFO
                            ON WFO.workflow_id = WF.id 
                            WHERE WS.id={$db->escape($getID)} AND WFO.type_rel = '1'  AND WF.Is_Active = '1'";
    $form = $db->query($str, "row");


    $form_json = json_decode($form['form_json'], true);

    $form_container = "style='margin: 0px auto;width:" . $form_json['WorkspaceWidth'] . "px;'";
    $form_size = "style=' background-color: #fff;height:" . $form_json['WorkspaceHeight'] . "px;'";

    $fieldEnabled = $form['fieldEnabled'];
    $fieldRequired = $form['fieldRequired'];
    $fieldHiddenValues = $form['fieldHiddenValue'];
}
?>

<div <?php echo $form_container; ?>>
    <div class="padding_5">
        <div class="body_header_container">
            <div class="head">
                <!-- ========== CSS Ribbon ========== -->
                <div class="ribbon-wrapper-green">
                    <div class="ribbon-green">
                        <?php
                        if ($_GET['view_type'] == "preview") {
                            echo "Preview";
                        } elseif ($_GET['view_type'] == "request") {
                            echo "Request";
                        } elseif ($_GET['view_type'] == "report" || $_GET['view_type'] == "update") {
                            echo "Report";
                        }
                        ?>
                    </div>
                </div>
                <div class="title_head formName">
                    <i class="icon-cogs"></i> (<u><label class="getFname"><?php echo $form['form_name']; ?></label></u>)
                </div>
            </div>
            <!-- ========== Attachmemt Files ========== -->
            <div class="padding_5 attached_file_container pr-nodes">

                <?php
                /* ========== Get Attachment files ========== */
                $path = "images/attachment";
                $id_encrypt = md5(md5($_GET['trackNo']));
                $dir = $path . "/" . $id_encrypt;
                /* ========== Get all files from the directory ========== */
                $getAttachment = $upload->getAllfiles_fromDirectory($dir);
                /* ========== List of files ========== */
                foreach ($getAttachment as $files) {
                    $get_extension = explode(".", $files);
                    $extension = $get_extension[count($get_extension) - 1];
                    /* ========== Determine if files is an image or not ========== */
                    $formats = array("jpg", "png", "JPG", "PNG", "GIF", "gif");
                    if (!in_array($extension, $formats)) {
                        echo '<div>';
                        echo '<form class="pull-left" method="POST" >';
                        echo '<div>';
                        echo '<input type="submit" class="cursor tip" data-original-title="Download Attachment"/><i class="icon-download"></i> ';
                        echo '<i class="icon-trash cursor tip removeFiles" data-original-title="Remove Attachment" data-file="' . $files . '" data-location="' . $dir . '/' . $files . '"></i>';
                        echo '</div>';
                        echo '<a class="download_attachment">';
                        echo '<div data-name="' . $files . '" class="AFiles_only avatar AFiles tip" data-original-title="' . $files . '" title="' . $files . '"><i class="icon-file"></i></div>';
                        echo '</a>';
                        //echo '<input type="submit"/>';
                        echo '<input type="hidden" value="' . $files . '" name="attachment_filename"/>';
                        echo '<input type="hidden" value="' . $dir . '/' . $files . '" name="attachment_location"/>';

                        echo '</form>';
                        echo '</div>';
                    } else {
                        echo '<div style="float:left;background-color:#fff;border:1px solid #D5D5D5;border-radius:5px;padding:5px;margin-left:5px;min-height:40px;">';
                        echo '<form class="pull-left" method="POST">';
                        echo '<div style="text-align: center;">';
                        echo '<input type="submit" style="opacity: 0;position: absolute;width: 10px;" class="cursor tip" data-original-title="Download Attachment"/><i class="icon-download"></i> ';
                        echo '<i class="icon-trash cursor tip removeFiles" data-original-title="Remove Attachment" data-file="' . $files . '" data-location="' . $dir . '/' . $files . '"></i>';
                        echo '</div>';
                        echo '<a class="download_attachment">';
                        echo '<img data-name="' . $files . '" src="/' . $dir . '/' . $files . '" width="25" height="25" class="AFiles imagetoPost avatar userPhoto personalPhoto userAvatar" data-original-title="' . $files . '" title="' . $files . '">';
                        echo '</a>';
                        //echo '<input type="submit"/>';
                        echo '<input type="hidden" value="' . $files . '" name="attachment_filename"/>';
                        echo '<input type="hidden" value="' . $dir . '/' . $files . '" name="attachment_location"/>';
                        echo '</form>';
                        echo '</div>';
                    }
                }
                
                
                ?>

            </div>
            <?php
            if (count($getAttachment) != "0") {
                echo '<br /><br />';
            }
            ?>
            <div class="head pr-nodes">
                <div class="title_head_btn">
                    <?php
                    if ($_GET['requestID'] != 0) {
                        echo '<button class="btn-basicBtn padding_5 cursor showReply tip" data-type="1" data-f-id="' . $_GET['formID'] . '" data-id="' . $requestID . '" data-original-title="Add/View Comments" ><i class="icon-comment"></i></button> ';
                        //echo ' <button class="btn-basicBtn padding_5 cursor viewRequestComment tip" data-original-title="View Comments"><i class="icon-comments"></i></button> ';
                        // //for updating the fields by workflow stage
                        // $request_id = $_GET['requestID'];
                        // $form_id  = $_GET['formID'];
                        // $results = $db->query("SELECT form_table_name FROM tb_workspace WHERE id = {$db->escape($getID)}", 'row');
                        // $tblname = $results['form_table_name'];
                        // $sqlStr_getFieldsUpdate = "SELECT WFO.workflow_id, WFO.buttonStatus,WFO.fieldEnabled, WFO.fieldRequired, WFO.fieldHiddenValue FROM $tblname form, tb_workspace ws LEFT JOIN tbworkflow w ON w.form_id = ws.id
                        //                   LEFT JOIN tbworkflow_objects wfo ON w.id=wfo.workflow_id WHERE wfo.object_id = form.Node_ID AND 
                        //                   w.id = form.Workflow_ID AND form.ID = $request_id AND ws.id = $form_id";
                        // $getFieldsUpdate = $db->query($sqlStr_getFieldsUpdate,"row");
                        // $fieldEnabled = $getFieldsUpdate['fieldEnabled'];
                        // $fieldRequired = $getFieldsUpdate['fieldRequired'];
                        // $fieldHiddenValues = $getFieldsUpdate['fieldHiddenValue'];
                    }
                    if ($_GET['view_type'] != "update") {
                    echo '<button class="btn-basicBtn padding_5 cursor tip viewAuditLogs" data-original-title="View Logs"><i class="icon-book"></i></button> ';
                    echo '<button class="btn-basicBtn padding_5 cursor tip printForm" data-original-title="Print Form"><i class="icon-print"></i></button> ';
                    echo '<span class="viewer_action"></span> ';
                    echo '<button class="btn-basicBtn padding_5 cursor tip" data-original-title="Add Files">';
                    echo '<form id="fille_attach" method="post" enctype="multipart/form-data" action="/ajax/request_attachment">';
                    echo '<input type="file" data-action-id="2" value="upload" name="file" id="file" size="24" data-action-type="attachFile" style="width: 10px;opacity: 0;position:absolute;" class="cursor upfile">';
                    echo '<input type="text" name="getFormID" id="getFormID" value="' . $_GET['formID'] . '" data-type="longtext" class="display getFields" />';
                    echo '<input type="text" name="getID" id="getID" value="' . $_GET['requestID'] . '" data-type="longtext" class="display getFields" />';
                    echo '<input type="text" name="getTrackNo" id="getTrackNo" value="' . $_GET['trackNo'] . '" data-type="longtext" class="display getFields" />';
                    echo '<i class="icon-paperclip"></i>';
                    echo '</form></button> ';
                    echo '<img src="/images/loader/load.gif" class="display attachFiles"/>';
                    }else{
                        echo '<button class="btn-basicBtn padding_5 cursor tip printForm" data-original-title="Print Form"><i class="icon-print"></i></button> ';
                    }
                    ?>


                </div>
                <div class="" style="float: right;width: 50%;margin-top: -2px;margin-right: 10px;text-align: right;">
                    <select id="actionRequestButton" class="input-select">
                        <option value="0">-------------Select Button-------------</option>
                        <?php
                        $buttonJSON = json_decode($form['buttonStatus'], true);
                        if ($_GET['view_type'] == "request") {
                            // echo print_r($buttonJSON);
                            foreach ($buttonJSON as $key => $value) {
                                echo '<option value="' . $buttonJSON[$key]["button_name"] . '" data-workflow-id="' . $form['workflow_id'] . '" action="' . $buttonJSON[$key]["child_id"] . '" message="' . $buttonJSON[$key]["message"] . '">' . $buttonJSON[$key]["button_name"] . '</option>';
                            }
                        }
                        ?>
                    </select>

                    <input id="goButton" type="button" class="btn-basicBtn " value="Go">
                </div>
            </div>
            <!-- ========== TrackNo, Requestor, Status, Processor ========== -->
            <?php
            if ($requestID != '0') {
                $search = new search();
                $result = $search->getManyRequest($requestID, "ID", $getID, 0, 1);
                //if($_GET['view_type']!="preview" && count($result)==0){
                //  header("location:/");
                //}
                ?>
                <br>
                <div class="head pr-nodes">
                    <div class="title_head">
                        <label>Tracking Number:</label><label id="trackno_display" style="color:#515E70;font-weight: normal;margin-left: 5px;margin-right: 5px"></label>
                        <label>Requestor:</label><label id="requestor_display" style="color:#515E70;font-weight: normal;margin-left: 5px;margin-right: 5px"></label>
                    </div>
                    <div class="title_head" style="float: right">
                        <label id="lblprocessor_display">Processor:</label><label id="processor_display" style="color:#515E70;font-weight: normal;margin-left: 5px;margin-right: 5px"></label>
                        <label>Status:</label><label id="status_display" style="color:#515E70;font-weight: normal;margin-left: 5px;margin-right: 5px"></label>
                    </div>
                </div>

                <?php
            }
            ?>
            <!-- ========== Preview Content ========== -->
            <div <?php echo $form_size; ?>>
                <div class="preview_content ui-droppable ui-resizable" style="padding: 5px;position: relative;min-height: 500px;background-color: #fff;">
                    <form id="frmrequest" method="POST" action="/ajax/request" >
                        <div class="display">
                            <input type="text" name="FormID" id="FormID" value="<?php echo $_GET['formID']; ?>" data-type="longtext" class="getFields" />
                            <input type="text" name="WorkflowId" id="WorkflowId" value="<?php echo $form['workflow_id']; ?>" data-type="longtext" class="getFields" />
                            <input type="text" name="ID" id="ID" value="<?php echo $_GET['requestID']; ?>" data-type="longtext" class="getFields" />
                            <input type="text" name="TrackNo" id="TrackNo" data-type="longtext" class="getFields" />
                            <input type="text" name="Requestor" value="<?php echo $auth['id']; ?>" id="Requestor" data-type="longtext" class="getFields" />
                            <input type="text" name="CurrentUser" current-user-name="<?php echo $auth['display_name']; ?>" value="<?php echo $auth['id']; ?>" id="CurrentUser" data-type="longtext" class="getFields" />
                            <input type="text" name="Status" id="Status" data-type="longtext" class="getFields" />
                            <input type="text" name="Processor" value="<?php echo $auth['id']; ?>" id="Processor" data-type="longtext" class="getFields" />
                            <input type="text" name="LastAction" id="LastAction" value='<?php echo $form['buttonStatus']; ?>' data-type="longtext" class="getFields" />
                            <input type="text" name="DateCreated" id="DateCreated" data-type="longtext" class="getFields" />
                            <input type="text" name="DateUpdated" id="DateUpdated" data-type="longtext" class="getFields" />
                            <input type="text" name="CreatedBy" value="<?php echo $auth['id']; ?>" id="CreatedBy" data-type="longtext" class="getFields" />
                            <input type="text" name="UpdatedBy" value="<?php echo $auth['id']; ?>" id="UpdatedBy" data-type="longtext" class="getFields" />
                            <input type="text" name="Unread" id="Unread" data-type="longtext" class="getFields" />
                            <input type="text" name="Node_ID" id="Node_ID" data-type="longtext" class="getFields" />
                            <input type="text" name="Workflow_ID" id="Workflow_ID" data-type="longtext" class="getFields" />
                            <input type="text" name="Mode" id="Mode" value="formApproval" data-type="longtext" class="getFields" />
                            <input type="text" name="imported" id="imported" data-type="longtext" class="getFields" />
                            <input type="text" name="computedFields" id="computedFields" />
                            <input type="text" name="fieldEnabled" id="fieldEnabled" value=' <?php echo $fieldEnabled; ?> ' data-type="longtext" class="getFields" />
                            <input type="text" name="KeywordsField" id="KeywordsField" data-type="longtext" class="" />
                            <input type="text" name="Repeater_Data" id="Repeater_Data" data-type="longtext" class="" />
                            <input type="text" name="Editor" id="Editor" data-type="longtext" class="" />
                            <input type="text" name="Department_Name" value="<?php echo $userDepartmentName; ?>" id="Department_Name" data-type="longtext" class="" />

                            <!-- ========== GET FIELD ENABLED, FIELD REQUIRED AND FIELD HIDDEN VALUES ========== -->
                            <div class="fieldEnabled"><?php echo $fieldEnabled; ?></div>
                            <div class="fieldRequired"><?php echo $fieldRequired; ?></div>
                            <div class="fieldHiddenValues"><?php echo $fieldHiddenValues; ?></div>

                            <div class="fieldEnabled_default"><?php echo $fieldEnabled; ?></div>
                            <div class="fieldRequired_default"><?php echo $fieldRequired; ?></div>
                            <div class="fieldHiddenValues_default"><?php echo $fieldHiddenValues; ?></div>
                            <input type="text" class="preview-nodes" value="<?php
                            if (isset($_GET['type']) && $_GET['type'] == "flowchart" || $_GET['type'] == "orgchart") {
                                echo "true";
                            } else {
                                echo "false";
                            }
                            ?>">
                            <!-- ========== Files Json ========== -->
                            <input type="text" name="attachment_files" id="view_attachment_files" />
                        </div>
                        <script>
                            //$(document).ready(function(){
                            var pathname = window.location;
                            if (getParametersName("view_type", pathname) == "preview" || getParametersName("view_type", pathname) == "report") {
                                var pid = window.opener["pid"];
                                var parseJson_data = jQuery.parseJSON(pid);
                                // Btn Content
                                var workspace_btn = parseJson_data.BtnName;
                                var get_btn = workspace_btn.split(",");
                                for (var a = 0; a < get_btn.length; a++) {
                                    $(".input-select").append("<option>" + get_btn[a] + "</option>");
                                }
                                // Form Content   
                                var workspace_content = parseJson_data.WorkspaceContent;
                                var content = workspace_content.replace(new RegExp("setObject cursor_move", "g"), "setOBJ form_upload_photos").replace(new RegExp('disabled="disabled"', 'g'), "");
                                //console.log(content)
                                // Append To content preview form
                                $("#frmrequest").append(content);
                                $(".formName").hide();
                            }
                            //});
                        </script>
                        <?php
                        if ($_GET['view_type'] == "request" || $_GET['view_type'] == "update") {

                            if ($form['company_id'] == "0" || $form['company_id'] == $auth['company_id']) {
                                $workspace_content = str_replace('setObject cursor_move', 'setOBJ form_upload_photos', $form['form_content']);
                                $remove_disabled = str_replace('disabled="disabled"', '', $workspace_content);
                                 //$remove_disabled1 = str_replace('form_upload_builder_photos"', 'form_upload_builder_photos1', $remove_disabled);
                                
                                echo $remove_disabled;
                            }
                        }
                        ?>
                    </form>
                </div>
            </div>
            <div class="head">
                <div class="pr-nodes" style="float: left;margin-top: 5px;margin-left: 10px;">
                    <button class="btn-basicBtn padding_5 cursor printForm"><i class="icon-print"></i> Print</button>
                </div>
                <!-- <div class="pr-nodes" style="float: right;width: 50%;margin-top: -2px;margin-right: 20px;text-align: right">
                    <select class="input-select">
                        <option>-------------Select Button-------------</option>
                    </select>
                    <input type="submit" class="btn-basicBtn " value="Go">
                </div> -->
            </div>
            
        </div>
    </div>
</div>
<script>
    var ajaxTime = (new Date()).getTime();
    var getServerTime = $.ajax({
        "url": "ajax/getDateToday",
        "async":false,
        "type": "POST",
        "cache": false,
        "beforeSend": function( xhr ) {
            // xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
        },
        "data": { "access":"get_date" },
        "dataType": "html"
    }).done(function( data ) {
        var responseTime = (new Date()).getTime() - ajaxTime;

        var serverOBJTIME = new Date(data);

        serverOBJTIME = serverOBJTIME.setTime(serverOBJTIME.getTime() )
        
        var temp = $("body").data();

        temp.getServerTimeData = serverOBJTIME;
        $("body").data(temp);

        setInterval(function(){
            var temp = $("body").data();

            var localTime = new Date();
            var serverTime = new Date(temp.getServerTimeData);

            // console.log("\n\n\n");
            // console.log("local",localTime,"\nserver",serverTime);

            // var updatedServerTime = new Date(serverTime.getTime() + timeDiff);
            var updatedServerTime = new Date(serverTime.setHours(serverTime.getHours() + (localTime.getHours() - serverTime.getHours() ) ) ); //ADDING HOURS
            updatedServerTime = new Date(serverTime.setMinutes(serverTime.getMinutes() + (localTime.getMinutes() - serverTime.getMinutes() ) ) ); //ADDING MINUTES
            updatedServerTime = new Date(serverTime.setSeconds(serverTime.getSeconds() + (localTime.getSeconds() - serverTime.getSeconds() ) ) ); //ADDING SECONDS
            
            temp.getServerTimeData = updatedServerTime;
            // alert(updatedServerTime)
            // console.log("updatedServerTime")
            // console.log(updatedServerTime);
            $("body").data(temp);
        },1000)
    }).fail(function() {
        console.log("SERVER DATE : ERROR ON GETTING AJAX POST METHOD SERVER TIME.");
    })

    function getUpdatedServerTime() {
        if (typeof $("body").data() != "undefined") {
            if (typeof $("body").data().get_counter_data != "undefined") {
                if (typeof $("body").data().get_counter_data.getDateTime != "undefined") {
                    return $("body").data().get_counter_data.getDateTime;
                }
            }else{
                return $("body").data().getServerTimeData;
            }
        }
        return "";
    }
    function getObjects(obj, key, val) {
        var objects = [];
        for (var i in obj) {
            if (!obj.hasOwnProperty(i))
                continue;
            if (typeof obj[i] == 'object') {
                objects = objects.concat(getObjects(obj[i], key, val));
            } else if (i == key && obj[key] == val) {
                objects.push(obj);
            }
        }
        return objects;
    }
    function makeOnChange(fieldAffected, fieldWithComputationParam, eventAddressNamespace) {
        var fieldWithComputation = $(fieldWithComputationParam);
        // console.log("check affected")
        // console.log(fieldAffected)
        if (fieldWithComputation.attr("default-formula-value")) {
            var event_string = "keyup change";
            // var field_affected = $(fieldAffected);
            // var field_typing = field_affected.filter(function(index, elem){
            //     if($(elem).prop("tagName") == "TEXTAREA") {
            //         return true;
            //     }else if($(elem).attr("type")){
            //         if($(elem).attr("type") == "text" && !$(elem).hasClass("hasDatepicker")){
            //             return true;
            //         }
            //     }
            // });
            // if(field_typing.length >= 1 ){
            //     var event_string = "keyup";
            // }else{
            //     var event_string = "change";
            // }
            
            if (typeof eventAddressNamespace == "undefined") {
                //do nothing

            } else {
                event_string = "keyup." + eventAddressNamespace + " change." + eventAddressNamespace;//namespace added for destroying repeated events
                // var field_affected = $(fieldAffected);
                // if(
                //     field_affected.prop("tagName") == "TEXTAREA" ||
                //     field_affected.attr("type") == "text"
                // ){
                //     event_string = "keyup." + eventAddressNamespace;
                // }else{
                //     event_string = "change." + eventAddressNamespace;
                // }
            }
            // console.log(event_string)
            // console.log("eto na ba un")
            // console.log(fieldAffected)
            if ($(fieldAffected).attr("event-id-from")) {
                var ids_event_from = $(fieldAffected).attr("event-id-from");
                var array_ids_event_from = ids_event_from.split(",");
                if (array_ids_event_from.indexOf(fieldWithComputation.closest(".setOBJ").attr("data-object-id")) >= 0) {

                } else {
                    $(fieldAffected).attr("event-id-from", $(fieldAffected).attr("event-id-from") + "," + fieldWithComputation.closest(".setOBJ").attr("data-object-id"));
                }
            } else {
                //console.log($(fieldAffected).attr("event-id-from", "" + fieldWithComputation.closest(".setOBJ").attr("data-object-id")));
            }
            // console.log("HAYS")
            // console.log(fieldWithComputation)

            $(fieldAffected).on(event_string, {"fieldWithComputation": fieldWithComputation}, function(e) {
                // e.stopPropagation();//AYAW GUMANA :<<<
                // event.stopPropagation();//AYAW GUMANA :<<<
                var fieldWithComputation = e.data.fieldWithComputation;
                // try{
                // console.log("ETO NGA BA UN?")
                // console.log(fieldWithComputation)
                var string_default_val = "" + fieldWithComputation.attr("default-formula-value");
                // console.log("eto ung formula")
                // console.log(string_default_val)
                // console.log(fieldWithComputation)
                if (string_default_val.indexOf("@Lookup") >= 0) {
                    return;
                }
                if (string_default_val.indexOf("@LookupWhere") >= 0) {
                    return;
                }
                if (string_default_val.indexOf("@LookupGetMin") >= 0) {
                    return;
                }
                if (string_default_val.indexOf("@LookupGetMax") >= 0) {
                    return;
                }
                if (string_default_val.indexOf("@LookupSDev") >= 0) {
                    return;
                }
                if (string_default_val.indexOf("@LookupAVG") >= 0) {
                    return;
                }
                if (string_default_val.indexOf(/^@Total\(*.\)$/) >= 0) {
                    return;
                }
                var string_field_formula = string_default_val;
                try {
                    splitted_default_val = string_default_val.match(/@GetAVG\(@[A-Za-z0-9_]*\)|@SDev\(@[A-Za-z0-9_]*\)|@GetMin\(@[A-Za-z0-9_]*\)|@GetMax\(@[A-Za-z0-9_]*\)|@Sum\(@[A-Za-z0-9_]*\)|@[a-zA-Z0-9_]*\[[A-Za-z]*\]|@[a-zA-Z0-9_]*/g);
                } catch (error) {
                    //console.log("the formula value is not defined");
                }
                var is_number = "true";
                for (ctr = 0; ctr < splitted_default_val.length; ctr++) {
                    replace_param1 = splitted_default_val[ctr].trim();
                    if (replace_param1.match(/@Sum\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
                        replace_param1 = splitted_default_val[ctr].trim().match(/@Sum\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                        replace_param1 = replace_param1[1].replace("@", "");
                    } else if(replace_param1.match(/@GetMax\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null){
                        replace_param1 = splitted_default_val[ctr].trim().match(/@GetMax\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                        replace_param1 = replace_param1[1].replace("@", "");
                    } else if(replace_param1.match(/@GetMin\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null){
                        replace_param1 = splitted_default_val[ctr].trim().match(/@GetMin\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                        replace_param1 = replace_param1[1].replace("@", "");
                    } else if(replace_param1.match(/@SDev\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null){
                        replace_param1 = splitted_default_val[ctr].trim().match(/@SDev\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                        replace_param1 = replace_param1[1].replace("@", "");
                    } else if(replace_param1.match(/@GetAVG\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null){
                        replace_param1 = splitted_default_val[ctr].trim().match(/@GetAVG\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                        replace_param1 = replace_param1[1].replace("@", "");
                    } else {
                        replace_param1 = splitted_default_val[ctr].trim().replace("@", "");
                    }

                    element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');

                    if ($(fieldWithComputation).parents("tr").length >= 1) {
                        if ($(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]').length >= 1) {
                            element_in_computation = $(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                        } else if ($(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]').length >= 1) {
                            element_in_computation = $(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                            // console.log($(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
                        } else {
                            element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                        }
                    } else {
                        element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                    }

                    if (element_in_computation.length >= 1) {
                    } else {
                        continue;
                    }

                    if (element_in_computation.attr("data-input-type") && element_in_computation.attr("data-input-type") == "Currency") {
                        replace_param2 = element_in_computation.val().replace(/,/g, "");
                    } else {
                        replace_param2 = element_in_computation.val();
                    }

                    if ($.isNumeric($.trim(replace_param2))) {

                    } else {
                        is_number = "false";
                        break;
                    }
                }
                for (ctr = 0; ctr < splitted_default_val.length; ctr++) {
                    replace_param1 = splitted_default_val[ctr].trim();
                    if(replace_param1.match(/@Sum\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null){
                        
                        var second_fn = "@Sum";
                    }
                    if(replace_param1.match(/@GetMax\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null){
                        var second_fn = "@GetMax";
                    }
                    if(replace_param1.match(/@GetMin\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null){
                        
                        var second_fn = "@GetMin";
                    }
                    if(string_default_val.match(/@SDev\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null){

                        var second_fn = "@SDev";
                    }
                    if(string_default_val.match(/@GetAVG\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null){

                        var second_fn = "@GetAVG";
                    }
                    if ($(fieldWithComputation).parents("tr").length >= 1) {
                        if ($(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]').length >= 1) {
                            element_in_computation = $(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                            // console.log($(fieldWithComputation).parents("tr").find('[rep-original-name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
                            // }else{
                            //     element_in_computation = $(fieldWithComputation).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                            //     console.log($(fieldWithComputation).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
                            // }
                        } else if ($(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]').length >= 1) {
                            element_in_computation = $(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                            // console.log($(this_self_ele).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
                        } else {
                            element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                        }
                    } else {
                        element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                        // console.log($(fieldWithComputation).parents("tr").find('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]'));
                    }
                    // element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');
                    if (replace_param1 == "") {
                        continue;
                    }
                    if (element_in_computation.length >= 1 && (string_default_val.match(/@GetAVG/) == null && string_default_val.match(/@SDev/) == null && replace_param1.match(/@Sum/) == null && replace_param1.match(/@GetMax/) == null && replace_param1.match(/@GetMin/) == null) ) {
                            var field_type = "";
                            if(typeof element_in_computation.attr("type") !== "undefined"){
                                    if(element_in_computation.attr("type") == "radio"){
                                            field_type = "radio";
                                    }
                            }
                            if (element_in_computation.attr("data-input-type") && element_in_computation.attr("data-input-type") == "Currency") {
                                replace_param2 = element_in_computation.val().replace(/,/g, "");
                            } else {
                                if(field_type == "radio"){
                                        replace_param2 = $('[name="'+element_in_computation.attr("name")+'"]:checked').val();
                                        if (!replace_param2) {
                                            replace_param2 = "";
                                        }
                                }else{
                                        replace_param2 = element_in_computation.val();
                                }
                                
                            }

                        if (is_number == "false") {
                            if (element_in_computation.attr("data-type") == "float") {
                                string_default_val = string_default_val.replace(replace_param1, "Number('" + "" + replace_param2.replace(/\"/g, "\\\"") + "" + "')");
                            } else if (element_in_computation.attr("data-type") == "longtext") {
                                replace_param2 = replace_param2.replace(/\\/g, "\\\\");
                                replace_param2 = replace_param2.replace(/\"/g, "\\\"");
                                // string_default_val = string_default_val.replace(replace_param1,"\""+replace_param2.replace(/\\/g,"\\\\")+"\"");
                                string_default_val = string_default_val.replace(replace_param1, "\"" + replace_param2 + "\"");
                            } else {
                                string_default_val = string_default_val.replace(replace_param1, "\"" + replace_param2.replace(/\"/g, "\\\"") + "\"");
                            }
                        } else {
                            string_default_val = string_default_val.replace(replace_param1, replace_param2);
                        }
                    } else if (element_in_computation.length == 0 || (string_default_val.match(/@GetAVG/) != null || string_default_val.match(/@SDev/) != null || replace_param1.match(/@Sum/) != null || replace_param1.match(/@GetMax/) != null || replace_param1.match(/@GetMin/) != null) ) {
                        if(typeof second_fn !== "undefined"){ //di na kailangan nito
                            // if(second_fn == "@Sum"){
                            //     replace_param1 = "@Sum("+replace_param1+")";
                            // }else if(second_fn == "@GetMax"){
                            //     replace_param1 = "@GetMax("+replace_param1+")";
                            // }else if(second_fn == "@GetMin"){
                            //     replace_param1 = "@GetMin("+replace_param1+")";
                            // }
                        }
                        if (replace_param1.indexOf("@Today") >= 0) {
                            var this_today = new Date(getUpdatedServerTime());
                            this_today = this_today.getFullYear() + "-" + StrRight("0" + (this_today.getMonth() + 1), 2) + "-" + StrRight("0" + this_today.getDate(), 2);
                            string_default_val = string_default_val.replace(replace_param1, "\"" + this_today + "\"");
                        } else if (replace_param1.indexOf("@Now") >= 0) {
                            var this_today = new Date(getUpdatedServerTime());
                            this_today = this_today.getFullYear() + "-" + StrRight("0" + (this_today.getMonth() + 1), 2) + "-" + StrRight("0" + this_today.getDate(), 2) + " " + StrRight("0" + this_today.getHours(), 2) + ":" + StrRight("0" + this_today.getMinutes(), 2) + ":" + StrRight("0" + this_today.getSeconds(), 2);
                            string_default_val = string_default_val.replace(replace_param1, "\"" + this_today + "\"");
                        } else if (replace_param1.indexOf("@RequestID") >= 0) {
                            var getID = $("#ID").val();
                            string_default_val = string_default_val.replace(replace_param1, "\"" + getID + "\"");
                        } else if (replace_param1.indexOf("@Department") >= 0) {
                            var getDepName = $("[name='Department_Name']").val();
                            string_default_val = string_default_val.replace(replace_param1, "\"" + getDepName + "\"");
                        } else if (replace_param1.match(/\[[A-Za-z]*\]/) != null) {//FOR SUM AVG ETC FORMULA
                            var fieldName = replace_param1.replace(/\[[A-Za-z]*\]|@/g, "");
                            var formula_function = replace_param1.match(/\[[A-Za-z]*\]/);
                            var get_fields_value = "(";
                            if (formula_function[0] == "[sum]") {
                                get_fields_value = get_fields_value + "Number('" + $('[name="' + fieldName + '"]').val() + "')";
                                $('[rep-original-name="' + fieldName + '"]').each(function() {
                                    get_fields_value = get_fields_value + " + Number('" + $(this).val() + "')";
                                });
                                get_fields_value = get_fields_value + ")";
                                string_default_val = string_default_val.replace(replace_param1, "" + get_fields_value + "");
                            }
                            if (formula_function[0] == "[Last]") {
                                if ($('[rep-original-name="' + fieldName + '"]').length >= 1) {
                                    var element_in_computation_last = $('[rep-original-name="' + fieldName + '"]').last();
                                    if ($.isNumeric(element_in_computation_last.val())) {
                                        get_fields_value = get_fields_value + "" + element_in_computation_last.val() + "";
                                    } else {
                                        get_fields_value = get_fields_value + "'" + element_in_computation_last.val() + "'";
                                    }
                                    get_fields_value = get_fields_value + ")";
                                    string_default_val = string_default_val.replace(replace_param1, "" + get_fields_value + "");
                                } else if ($('[name="' + fieldName + '"]').length >= 1) {
                                    var element_in_computation_last = $('[name="' + fieldName + '"]').last();
                                    if ($.isNumeric(element_in_computation_last.val())) {
                                        get_fields_value = get_fields_value + "" + element_in_computation_last.val() + "";
                                    } else {
                                        get_fields_value = get_fields_value + "'" + element_in_computation_last.val() + "'";
                                    }
                                    get_fields_value = get_fields_value + ")";
                                    string_default_val = string_default_val.replace(replace_param1, "" + get_fields_value + "");
                                }
                            }
                        } else if (replace_param1.match(/@Sum\(@[A-Za-z0-9_]*\)/g) != null) { //FOR @Sum(@Fieldname)
                            fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
                            var reg_exp = new RegExp(fieldName[1]+"|"+"'"+fieldName[1]+"'",'g');
                            if(fieldExists("\""+fieldName[1]+"\"") == true){
                                string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                            }
                            
                        } else if (replace_param1.match(/@GetMax\(@[A-Za-z0-9_]*\)/g) != null) { //

                            fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
                            var reg_exp = new RegExp(fieldName[1]+"|"+"'"+fieldName[1]+"'",'g');
                            if(fieldExists("\""+fieldName[1]+"\"") == true){
                                string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                            }
                            
                        } else if (replace_param1.match(/@GetMin\(@[A-Za-z0-9_]*\)/g) != null) { //
                            fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
                            var reg_exp = new RegExp(fieldName[1]+"|"+"'"+fieldName[1]+"'",'g');
                            if(fieldExists("\""+fieldName[1]+"\"") == true){
                                string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                            }
                            
                        } else if (replace_param1.match(/@SDev\(@[A-Za-z0-9_]*\)/g) != null) { //
                            fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
                            var reg_exp = new RegExp(fieldName[1]+"|"+"'"+fieldName[1]+"'",'g');
                            if(fieldExists("\""+fieldName[1]+"\"") == true){
                                string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                            }
                            
                        } else if (replace_param1.match(/@GetAVG\(@[A-Za-z0-9_]*\)/g) != null) { //
                            
                            fieldName = replace_param1.match(/\((@[A-Za-z0-9_]*)\)/);
                            var reg_exp = new RegExp(fieldName[1]+"|"+"'"+fieldName[1]+"'",'g');
                            if(fieldExists("\""+fieldName[1]+"\"") == true){
                                string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                            }
                            
                        }
                        //console.log("BADDDKERT", replace_param1);
                    }
                }
                if (string_default_val.indexOf("@") >= 0) {
                    string_default_val = string_default_val.replace(/@/g, "");
                }
                if (string_default_val.indexOf(/\'/g) >= 0) {
                    string_default_val = string_default_val.replace(/\'/g, "\'");
                }
                // console.log(string_default_val)
                // if(string_default_val.match(/\\/g) != null){
                //  string_default_val = string_default_val.replace(/\\/g,"\\\\");
                // }
                // console.log(string_default_val)
                if (string_default_val.match(/\"/g) != null) {
                    string_default_val = string_default_val.replace(/\"/g, "\"");
                }
                //console.log("TEST")
                //console.log(string_default_val)
                var eval_status = "not ok";
                try {
                    eval(string_default_val);
                    eval_status = "ok";
                    //console.log("OK",string_default_val,fieldWithComputation)
                } catch (error) {
                    eval_status = "not ok";
                    //console.log("NOT OK",string_default_val,fieldWithComputation,error);
                }
                // console.log("NAKARATING??")
                // console.log(fieldWithComputation)
                // console.log($(this))
                if (eval_status == "ok") {
                    if (string_default_val.indexOf("Lookup") >= 0) {
                        //data = [];
                        //fieldName = fieldWithComputation.attr("name");
                        //formula = string_default_val;
                        //data.push({
                        //    FieldName: fieldName,
                        //    Formula: formula
                        //});
                        //$.get('/ajax/ajaxformula', {
                        //    data: JSON.stringify(data)
                        //}, function(data) {
                        //    data = JSON.parse(data);
                        //    console.log("uung sa onchange");
                        //    console.log(data);
                        //    $('[name="' + data[0].FieldName + '"]').val(data[0].FieldValue);
                        //});
                    } else if (string_default_val.indexOf("RecordCount") >= 0) {
                        //
                    } else {
                        if (eval(string_default_val) == "Infinity") {
                            fieldWithComputation.val("Cannot divide by zero");
                        } else if (eval(string_default_val) == "Invalid Date") {
                            //do not place any value
                        } else {
                            if (fieldWithComputation.hasClass("hasDatepicker") && fieldWithComputation.attr("data-type") == "date") {
                                fieldWithComputation.val(eval(string_default_val));
                                fieldWithComputation.val(ThisDate(fieldWithComputation.val()).formatDate("Y-m-d"));
                            } else if (fieldWithComputation.hasClass("hasDatepicker") && fieldWithComputation.attr("data-type") == "dateTime") {
                                fieldWithComputation.val(eval(string_default_val));
                                fieldWithComputation.val(ThisDate(fieldWithComputation.val()).formatDate("Y-m-d H:i"));
                            } else {
                                fieldWithComputation.val(eval(string_default_val));
                                if (fieldWithComputation.val() == "NaN") {
                                    fieldWithComputation.val("Not a valid computation")
                                }
                            }
                        }
                    }
                } else {
                    //console.log(fieldWithComputation,"EVAL STAT NOT OK");
                    //console.log(string_default_val)
                }


                // }catch(error){
                //   alert("nag error??")
                // }
                var reg_eks = new RegExp("@" + fieldWithComputation.attr("name") + "(?![a-zA-Z0-9_])", "g");
                if (fieldWithComputation.attr("default-formula-value").match(reg_eks) == null) {
                    fieldWithComputation.change();
                }
                //console.log(string_default_val)
                //console.log("\n\n\n\n\n\n\n\n\n\n\n\n")
            });
            //}
        }

    }
    function defaultComputed(data_obj_id, the_field_ele, this_element, eventAddressNamespace) {

        the_field = the_field_ele;
        this_self_ele = $(this_element);
        var string_default_val = "" + $(this_self_ele).find(".getFields_" + data_obj_id).attr("default-formula-value");

        string_default_val = "" + $(this_self_ele).find(".getFields_" + data_obj_id).attr("default-formula-value");

        if (string_default_val.indexOf("@Lookup") >= 0) {
            return;
        }

        if (string_default_val.indexOf("@RecordCount") >= 0) {
            return;
        }
        if (string_default_val.indexOf("@LookupWhere") >= 0) {
            return;
        }
        if (string_default_val.indexOf("@LookupSDev") >= 0) {
            return;
        }
        if (string_default_val.indexOf("@LookupAVG") >= 0) {
            return;
        }
        if (string_default_val.indexOf(/^@Total\(*.\)$/) >= 0) {
            return;
        }

        splitted_default_val = string_default_val.match(/@GetAVG\(@[A-Za-z0-9_]*\)|@SDev\(@[A-Za-z0-9_]*\)|@GetMin\(@[A-Za-z0-9_]*\)|@GetMax\(@[A-Za-z0-9_]*\)|@Sum\(@[A-Za-z0-9_]*\)|@[a-zA-Z0-9_]*\[[A-Za-z]*\]|@[a-zA-Z0-9_]*/g);
        console.log("\n\n\n\nHEY",string_default_val,"  ",splitted_default_val)

        if (splitted_default_val != null) { //KAPAG NAG NULL UNG MATCH OR SPLITTED VALUES
            var is_number = "true";
            for (ctr = 0; ctr < splitted_default_val.length; ctr++) {
                replace_param1 = splitted_default_val[ctr].trim();
                element_in_computation = $('[name="' + $.trim(replace_param1.split(/@|\(|\)/g).join("")) + '"]');

                replace_param2 = element_in_computation.val();
                if (element_in_computation.length >= 1) {
                } else {
                    continue;
                }
                if ($.isNumeric(replace_param2)) {
                } else {
                    is_number = "false";
                    break;
                }
            }
            // console.log("TESTING THIS GREAT FORMULA");
            for (ctr = 0; ctr < splitted_default_val.length; ctr++) {
                
                replace_param1 = splitted_default_val[ctr].trim();
                if (replace_param1.match(/@Sum\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null) {
                    replace_param1 = splitted_default_val[ctr].trim().match(/@Sum\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                    replace_param1 = replace_param1[1].replace("@", "");
                } else if(replace_param1.match(/@GetMax\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null){
                    replace_param1 = splitted_default_val[ctr].trim().match(/@GetMax\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                    replace_param1 = replace_param1[1].replace("@", "");
                } else if(replace_param1.match(/@SDev\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null){
                    replace_param1 = splitted_default_val[ctr].trim().match(/@SDev\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                    replace_param1 = replace_param1[1].replace("@", "");
                } else if(replace_param1.match(/@GetMin\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null){
                    replace_param1 = splitted_default_val[ctr].trim().match(/@GetMin\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                    replace_param1 = replace_param1[1].replace("@", "");
                } else if(replace_param1.match(/@GetAVG\(@[A-Za-z][A-Za-z0-9_]*\)/g) != null){
                    replace_param1 = splitted_default_val[ctr].trim().match(/@GetAVG\((@[A-Za-z][A-Za-z0-9_]*)\)/);
                    replace_param1 = replace_param1[1].replace("@", "");
                } else {
                    replace_param1 = splitted_default_val[ctr].trim().replace("@", "");
                }
                if ($(this_self_ele).parents("tr").length >= 1 && $(this_self_ele).parents("table[repeater-table='true']").length>0) { // kapag ung may formula ay nasa loob ng row
                    if ($(this_self_ele).parents("tr").find('[rep-original-name="' + replace_param1 + '"]').length >= 1) {
                        element_in_computation = $(this_self_ele).parents("tr").find('[rep-original-name="' + replace_param1 + '"]');
                    } else if ($(this_self_ele).parents("tr").find('[name="' + replace_param1 + '"]').length >= 1) {
                        element_in_computation = $(this_self_ele).parents("tr").find('[name="' + replace_param1 + '"]');
                    } else {
                        element_in_computation = $('[name="' + replace_param1 + '"]');
                    }
                /*} else if($("[name='"+replace_param1+"']").parents("tr").length >= 1){// kapag ung fieldname sa formula ay nasa loob ng row
                    element_in_computation = $("[name='"+replace_param1+"']").add('[rep-original-name="' + replace_param1 + '"]');*/
                } else {
                    element_in_computation = $('[name="' + replace_param1 + '"]');
                    if(splitted_default_val[ctr].trim().match(/@Sum\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null){
                        if (splitted_default_val[ctr].trim().match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@","") == replace_param1 && element_in_computation.length >= 1) {
                            if (typeof element_in_computation.attr("event-id-from") != "undefined") {
                                if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

                                } else {
                                    element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
                                }
                            } else {
                                element_in_computation.attr("event-id-from", data_obj_id);
                            }
                        }
                        var second_fn = "@Sum";
                    }
                    if(splitted_default_val[ctr].trim().match(/@SDev\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null){
                        if (splitted_default_val[ctr].trim().match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@","") == replace_param1 && element_in_computation.length >= 1) {
                            if (typeof element_in_computation.attr("event-id-from") != "undefined") {
                                if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

                                } else {
                                    element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
                                }
                            } else {
                                element_in_computation.attr("event-id-from", data_obj_id);
                            }
                        }
                        var second_fn = "@SDev";
                    }
                    if(splitted_default_val[ctr].trim().match(/@GetMax\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null){
                        if (splitted_default_val[ctr].trim().match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@","") == replace_param1 && element_in_computation.length >= 1) {
                            if (typeof element_in_computation.attr("event-id-from") != "undefined") {
                                if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

                                } else {
                                    element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
                                }
                            } else {
                                element_in_computation.attr("event-id-from", data_obj_id);
                            }
                        }
                        var second_fn = "@GetMax";
                    }
                    if(splitted_default_val[ctr].trim().match(/@GetMin\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null){
                        if (splitted_default_val[ctr].trim().match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@","") == replace_param1 && element_in_computation.length >= 1) {
                            if (typeof element_in_computation.attr("event-id-from") != "undefined") {
                                if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

                                } else {
                                    element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
                                }
                            } else {
                                element_in_computation.attr("event-id-from", data_obj_id);
                            }
                        }
                        var second_fn = "@GetMin";
                    }
                    if(splitted_default_val[ctr].trim().match(/@GetAVG\((@[A-Za-z][A-Za-z0-9_]*)\)/) != null){
                        if (splitted_default_val[ctr].trim().match(/\((@[A-Za-z][A-Za-z0-9_]*)\)/)[1].replace("@","") == replace_param1 && element_in_computation.length >= 1) {
                            if (typeof element_in_computation.attr("event-id-from") != "undefined") {
                                if (element_in_computation.attr("event-id-from").indexOf(data_obj_id) >= 0) {

                                } else {
                                    element_in_computation.attr("event-id-from", element_in_computation.attr("event-id-from") + "," + data_obj_id);
                                }
                            } else {
                                element_in_computation.attr("event-id-from", data_obj_id);
                            }
                        }
                        var second_fn = "@GetAVG";
                    }
                }

                // console.log($.trim(replace_param1.split(/@|\(|\)/g).join("")));
                // console.log(element_in_computation.attr("name"));

                if (replace_param1 == "") {
                    continue;
                }
				console.log("WALANG ELE",element_in_computation.length)
                if (element_in_computation.length >= 1 && (splitted_default_val[ctr].trim().match(/@GetAVG/) == null && splitted_default_val[ctr].trim().match(/@SDev/) == null && splitted_default_val[ctr].trim().match(/@Sum/) == null && splitted_default_val[ctr].trim().match(/@GetMax/) == null && splitted_default_val[ctr].trim().match(/@GetMin/) == null) ) {
                    console.log("TAAs")
					replace_param2 = element_in_computation.val();
                    // console.log("DC");
                    // console.log(element_in_computation);
                    try {
                        //if(element_in_computation.parents("tr").length >= 1){
                        //  if(the_field.attr("default-formula-value")){
                        //      if(the_field.attr("default-type")){
                        //          if(the_field.attr("default-type") == "computed"){
                        //              if(the_field.attr("default-formula-value").indexOf("@Sum") >= 0 ){
                        //                  element_in_computation = $(element_in_computation.selector+", [rep-original-name='"+$.trim(replace_param1.split(/@|\(|\)/g).join(""))+"']")
                        //                  element_in_computation.each(function(eqi){
                        //                      $(this).attr("event-id-from", the_field.parents(".setOBJ").eq(0).attr("data-object-id"));
                        //                  })
                        //              }
                        //          }
                        //      }
                        //  }
                        //}
                    } catch (errr) {
                    }
                    //if(this_self_ele.attr("name")=="TotalRunBal"){
                    //  console.log("ARRGH2   "+$.trim(replace_param1.split(/@|\(|\)/g).join("")))
                    //  console.log(this_self_ele.attr("default-formula-value"))
                    //  console.log(this_self_ele)
                    //  console.log(this_self_ele.attr("name"))
                    //  console.log(element_in_computation)
                    //  console.log("ARRGH2----")
                    //}
                    //console.log("PALA"+string_default_val)
                    //console.log("MAKEONCHANGE",element_in_computation,this_self_ele)
                    makeOnChange(element_in_computation, the_field, eventAddressNamespace);
                    if (is_number == "false") {//
                        if (element_in_computation.attr("data-type") == "float") {
                            string_default_val = string_default_val.replace(replace_param1, "Number('" + "" + replace_param2.replace(/\"/g, "\\\"") + "" + "')");
                        } else if (element_in_computation.attr("data-type") == "longtext") {
                            replace_param2 = replace_param2.replace(/\\/g, "\\\\");
                            replace_param2 = replace_param2.replace(/\"/g, "\\\"");
                            string_default_val = string_default_val.replace(replace_param1, "\"" + replace_param2 + "\"");
                        } else {
                            string_default_val = string_default_val.replace(replace_param1, "\"" + replace_param2.replace(/\"/g, "\\\"") + "\"");
                        }
                    } else {
                        string_default_val = string_default_val.replace(replace_param1, replace_param2);
                    }
                } else if (element_in_computation.length == 0 || (splitted_default_val[ctr].trim().match(/@GetAVG/) != null || splitted_default_val[ctr].trim().match(/@SDev/) != null || splitted_default_val[ctr].trim().match(/@Sum/) != null || splitted_default_val[ctr].trim().match(/@GetMax/) != null || splitted_default_val[ctr].trim().match(/@GetMin/) != null) ) {
                    var rep_param_w_at = "@" + replace_param1;
                    
                    if(typeof second_fn !== "undefined"){
                        if(second_fn == "@Sum"){
                            rep_param_w_at = "@Sum("+rep_param_w_at+")";
                        }else if(second_fn == "@GetMax"){
                            rep_param_w_at = "@GetMax("+rep_param_w_at+")";
                        }else if(second_fn == "@SDev"){
                            rep_param_w_at = "@SDev("+rep_param_w_at+")";
                        }else if(second_fn == "@GetMin"){
                            rep_param_w_at = "@GetMin("+rep_param_w_at+")";
                        }else if(second_fn == "@GetAVG"){
                            rep_param_w_at = "@GetAVG("+rep_param_w_at+")";
                        }
                    }
                    if (rep_param_w_at.indexOf("@Today") >= 0) {

                        var this_today = new Date(getUpdatedServerTime());
                        this_today = this_today.getFullYear() + "-" + StrRight("0" + (this_today.getMonth() + 1), 2) + "-" + StrRight("0" + this_today.getDate(), 2);

                        string_default_val = string_default_val.replace(rep_param_w_at, "\"" + this_today + "\"");
                    } else if (rep_param_w_at.indexOf("@Now") >= 0) {
                        var this_today = new Date(getUpdatedServerTime());
                        this_today = this_today.getFullYear() + "-" + StrRight("0" + (this_today.getMonth() + 1), 2) + "-" + StrRight("0" + this_today.getDate(), 2) + " " + StrRight("0" + this_today.getHours(), 2) + ":" + StrRight("0" + this_today.getMinutes(), 2) + ":" + StrRight("0" + this_today.getSeconds(), 2);
                        string_default_val = string_default_val.replace(rep_param_w_at, "\"" + this_today + "\"");
                    } else if (rep_param_w_at.indexOf("@RequestID") >= 0) {
                        var getID = $("#ID").val();
                        string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getID + "\"");
                    } else if (rep_param_w_at.indexOf("@CurrentUser") >= 0) {
                        //current_user_ele = $("#frmrequest").find('[name="CurrentUser"]').eq(0)
                        var getCurrentUser = "<?php echo $auth['display_name']; ?>";
                        string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getCurrentUser + "\"");
                    } else if (rep_param_w_at.indexOf("@Requestor") >= 0) {
                        //requestor_ele = $("#frmrequest").find('[name="Requestor"]').eq(0)
                        // requestor_ele = "<?php echo $auth['display_name']; ?>";
                        // $(this_self_ele).find(".getFields_" + data_obj_id).val(requestor_ele);
                        var getRequestorVal = "<?php echo $auth['display_name']; ?>";
                        string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getRequestorVal + "\"");
                    } else if (rep_param_w_at.indexOf("@TrackNo") >= 0) {

                        // var self_tn = $(this_self_ele);
                        // var gettingValueChangesTrackNo = setInterval(function() {
                        //     track_no_ele_val = track_no_ele.val();
                        //     if (track_no_ele_val == "") {
                        //         self_tn.find(".getFields_" + data_obj_id).val("");
                        //     } else {
                        //         self_tn.find(".getFields_" + data_obj_id).val(track_no_ele_val);
                        //         clearInterval(gettingValueChangesTrackNo);
                        //     }
                        // }, 100);
                        // $(this_self_ele).find(".getFields_" + data_obj_id).val(track_no_ele.val());
                        var track_no_ele = $("#frmrequest").find('[name="TrackNo"]').eq(0)
                        var getTrackNoVal = track_no_ele.val();
                        string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getTrackNoVal + "\"");
                    } else if (rep_param_w_at.indexOf("@Status") >= 0) {
                        // var self_s = $(this_self_ele);
                        // var gettingValueChangesStatus = setInterval(function() {
                        //     status_ele_val = status_ele.val();
                        //     if (status_ele_val == "") {
                        //         self_s.find(".getFields_" + data_obj_id).val("New request");
                        //     } else {
                        //         self_s.find(".getFields_" + data_obj_id).val(status_ele_val);
                        //         clearInterval(gettingValueChangesStatus);
                        //     }
                        // }, 100);
                        var status_ele = $("#frmrequest").find('[name="Status"]').eq(0);
                        var getStatusVal = status_ele.val();
                        string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getStatusVal + "\"");
                    } else if (rep_param_w_at.indexOf("@Department") >= 0) {
                        var getDepName = $("[name='Department_Name']").val();
                        string_default_val = string_default_val.replace(rep_param_w_at, "\"" + getDepName + "\"");
                    } else if (rep_param_w_at.match(/\[[A-Za-z]*\]/) != null) {//FOR SUM AVG ETC FORMULA
                        var fieldName = rep_param_w_at.replace(/\[[A-Za-z]*\]|@/g, "");
                        var formula_function = rep_param_w_at.match(/\[[A-Za-z]*\]/);
                        var get_fields_value = "(";
                        if (formula_function[0] == "[sum]") {
                            get_fields_value = get_fields_value + "Number('" + $('[name="' + fieldName + '"]').val() + "')";

                            makeOnChange($('[name="' + fieldName + '"]'), the_field, eventAddressNamespace);
                            $('[rep-original-name="' + fieldName + '"]').each(function() {
                                //
                                get_fields_value = get_fields_value + " + Number('" + $(this).val() + "')";
                            });
                            get_fields_value = get_fields_value + ")";
                            string_default_val = string_default_val.replace(rep_param_w_at, "" + get_fields_value + "");
                        }
                        if (formula_function[0] == "[Last]") {
                            if ($('[rep-original-name="' + fieldName + '"]').length >= 1) {
                                var element_in_computation_last = $('[rep-original-name="' + fieldName + '"]').last();
                                makeOnChange(element_in_computation_last, the_field, eventAddressNamespace);
                                if ($.isNumeric(element_in_computation_last.val())) {
                                    get_fields_value = get_fields_value + "" + element_in_computation_last.val() + "";
                                } else {
                                    get_fields_value = get_fields_value + "'" + element_in_computation_last.val() + "'";
                                }
                                get_fields_value = get_fields_value + ")";
                                string_default_val = string_default_val.replace(rep_param_w_at, "" + get_fields_value + "");
                            } else if ($('[name="' + fieldName + '"]').length >= 1) {
                                var element_in_computation_last = $('[name="' + fieldName + '"]').last();
                                makeOnChange(element_in_computation_last, the_field, eventAddressNamespace);
                                if ($.isNumeric(element_in_computation_last.val())) {
                                    get_fields_value = get_fields_value + "" + element_in_computation_last.val() + "";
                                } else {
                                    get_fields_value = get_fields_value + "'" + element_in_computation_last.val() + "'";
                                }
                                get_fields_value = get_fields_value + ")";
                                string_default_val = string_default_val.replace(rep_param_w_at, "" + get_fields_value + "");
                            }
                        }
                    } else if (rep_param_w_at.match(/@Sum\(@[A-Za-z0-9_]*\)/g) != null) { //FOR @Sum(@Fieldname)
                        fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
                        var reg_exp = new RegExp(fieldName[1]+"|"+"'"+fieldName[1]+"'",'g');
                        if(fieldExists("\""+fieldName[1]+"\"") == true){
                            string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                        }
                        makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
                    } else if (rep_param_w_at.match(/@GetMax\(@[A-Za-z0-9_]*\)/g) != null) { //

                        fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
                        var reg_exp = new RegExp(fieldName[1]+"|"+"'"+fieldName[1]+"'",'g');
                        if(fieldExists("\""+fieldName[1]+"\"") == true){
                            string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                        }
                        makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
                    } else if (rep_param_w_at.match(/@GetMin\(@[A-Za-z0-9_]*\)/g) != null) { //
                        fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
                        var reg_exp = new RegExp(fieldName[1]+"|"+"'"+fieldName[1]+"'",'g');
                        if(fieldExists("\""+fieldName[1]+"\"") == true){
                            string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                        }
                        makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
                    } else if (rep_param_w_at.match(/@SDev\(@[A-Za-z0-9_]*\)/g) != null) { //
                        fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
                        var reg_exp = new RegExp(fieldName[1]+"|"+"'"+fieldName[1]+"'",'g');
                        if(fieldExists("\""+fieldName[1]+"\"") == true){
                            string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                        }
                        makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
                    } else if (rep_param_w_at.match(/@GetAVG\(@[A-Za-z0-9_]*\)/g) != null) { //
                        fieldName = rep_param_w_at.match(/\((@[A-Za-z0-9_]*)\)/);
                        var reg_exp = new RegExp(fieldName[1]+"|"+"'"+fieldName[1]+"'",'g');
                        if(fieldExists("\""+fieldName[1]+"\"") == true){
                            string_default_val = string_default_val.replace(reg_exp, "'" + fieldName[1] + "'");
                        }
                        makeOnChange($('[name="' + fieldName[1].replace("@", "") + '"]'), the_field, eventAddressNamespace);
                    }
                }

            }
            //console.log("end of testing great formula",string_default_val)
            if (string_default_val.indexOf("@") >= 0) {
                string_default_val = string_default_val.replace(/@/g, "");
            }
            if (string_default_val.indexOf(/\'/g) >= 0) {
                string_default_val = string_default_val.replace(/\'/g, "\'");
            }
            if (string_default_val.match(/\"/g) != null) {
                string_default_val = string_default_val.replace(/\"/g, "\"");
            }
            // // console.log(string_default_val)
            // if(string_default_val.match(/\\/g) != null){
            //  string_default_val = string_default_val.replace(/\\/g,"\\\\");
            // }
            // // console.log(string_default_val)
            // if(string_default_val.match(/\"/g) != null){
            //  string_default_val = string_default_val.replace(/\"/g,"\\\"");
            // }
            // console.log("TESTZZZ")
            // console.log(string_default_val)
            // alert("WHOA")
            if (string_default_val.indexOf("Lookup") >= 0) {

            } else {
                var eval_parse_status = "";
                try {
                    eval(String("" + string_default_val));
                    eval_parse_status = "ok";
                    console.log(this_self_ele, "ok",string_default_val);
                } catch (e) {
                    eval_parse_status = "not ok";
                    console.log(this_self_ele,"not",string_default_val,e);
                }
                if (eval_parse_status == "ok") {
                    if (eval(String(string_default_val)) == "Infinity") {
                        $(this_self_ele).find(".getFields_" + data_obj_id).val("Cannot divide by zero");
                    } else if (eval(String(string_default_val)) == "Invalid Date") {
                        //do not place any value
                    } else {
                        //THIS IS THE STARTUP VALUE
                        $(this_self_ele).find(".getFields_" + data_obj_id).val(eval(String(string_default_val)));
                        if ($(this_self_ele).find(".getFields_" + data_obj_id).val() == "NaN") {
                            $(this_self_ele).find(".getFields_" + data_obj_id).val("Not a valid computation")
                        }
                    }
                }
            }
        }
        // }
    }

    function populateFormula(object,callBack) {
        if (typeof callBack == "undefined") {

        }
        var obj_name = "";
        if(object){
            obj_name = $(object).attr("name");
        }
        var data = [];
        $('.getFields').each(function(index) {
            if ($(this).attr('default-formula-value')) {
                var fieldName = $(this).attr('name');
                var formula = $(this).attr('default-formula-value');
                var process_formula = formula;
                var getFieldName = formula.match(/@[A-Za-z_][A-Za-z0-9_]*/g);

                if (getFieldName) {
                    for (var ctr = 0; ctr < getFieldName.length; ctr++) {
                        if ($('[name="' + getFieldName[ctr].replace("@", "") + '"]').length >= 1) {
                            var value_fn = $('[name="' + getFieldName[ctr].replace("@", "") + '"]').val();
                            process_formula = process_formula.replace(getFieldName[ctr], "'" + value_fn + "'");
                        }
                    }
                }
                if (process_formula.indexOf("@LookupGetMax") >= 0 || process_formula.indexOf("@LookupGetMin") >= 0 || process_formula.indexOf("@LookupSDev") >= 0 || process_formula.match(/^@Total\(.*\)$/) != null || process_formula.indexOf("@Lookup") >= 0 || process_formula.indexOf("@RecordCount") >= 0 ) {
                    data.push({
                        RequestID: $("#ID").val(),
                        FieldName: fieldName,
                        Formula: process_formula
                    });
					//console.log("OK SERVER FORMULAz");
                }
            }
        });

        //console.log(data);
        if(data.length >=1){
            $.get('/ajax/ajaxformula', {
                data: JSON.stringify(data)
            }, function(result) {
                // $("html").html(result)
                var result = JSON.parse(result);
                
                //console.log("AJAX SERVER FORMULA:",result);
                for (var index in result) {
                    var returnFieldName = result[index].FieldName;
                    var returnFieldValue = result[index].FieldValue;

                    //console.log(returnFieldName);
                    //console.log($('[name="' + returnFieldName + '"]'))
                    $('[name="' + returnFieldName + '"]').val(returnFieldValue);
                    if(obj_name != returnFieldName){
                         $('[name="' + returnFieldName + '"]').change();
                    }
                }
                if (typeof callBack != "undefined") {
                    callBack();
                }
            });
        }
    }

    function addRefreshEvent() {
        $("body").on("change", '[lookup-event-trigger="true"]', function() {
            populateFormula(this);
            computeVisibility();
        });
    }

    $(document).ready(function() {

        addRefreshEvent();
        setFieldsVisibility();
        
        populateFormula();
        

        $(".node-process-drag").css("border-top", "none");
        if ($(".preview-nodes").val() == "true") {
            $(".pr-nodes").remove();
        }
        try {
            var form_json_data = <?php
                        if (empty($form["form_json"])) {
                            echo '\'\'';
                        } else {
                            echo $form["form_json"];
                        }
                        ?>;
        } catch (error) {
            console.log("error on getting the form_json");
        }

        if (typeof form_json_data != "undefined" && form_json_data != '') {

            if ($(".setOBJ").length >= 1) {
                //fields having a defaultfields
                //set static values
                $(".setOBJ").each(function(eqi_setOBJ) {
                    var data_obj_id = $(this).attr("data-object-id");
                    var the_field = $(this).find(".getFields_" + data_obj_id);
                    if (the_field.attr("default-type")) {
                        if (the_field.attr("default-type") == "static") {
							if(typeof the_field.attr("default-static-value") != "undefined"){
								if(the_field.attr("default-static-value").length >= 1 ){
									the_field.val(the_field.attr("default-static-value"));
								}
							}
                        } else if (the_field.attr("default-type") == "computed") {

                        }
                    }
                });
                //set default values
                $(".setOBJ").each(function(eqi_setOBJ) {
                    var data_obj_id = $(this).attr("data-object-id");
                    //try{
                    if (typeof form_json_data.form_json["" + data_obj_id] != "undefined") {
                        var the_field = $(this).find(".getFields_" + data_obj_id);
                        if (
                                the_field.attr("type") && (
                                the_field.attr("type") == "radio" ||
                                the_field.attr("type") == "checkbox"
                                )
                                ) {
                            if (typeof form_json_data.form_json["" + data_obj_id].defaultValues != "undefined") {
                                $.each(form_json_data.form_json["" + data_obj_id].defaultValues, function(index, item) {
                                    var radio_check_strvalue = form_json_data.form_json["" + data_obj_id].defaultValues[index];
                                    if ($(the_field).eq(index).length >= 1 && $(the_field).eq(index).val() == radio_check_strvalue) {
                                        if($("#getID").val() == "0"){
											$(the_field).eq(index).prop("checked", true);
										}
                                    }
                                });
                            }

                        } else if (the_field.prop("tagName") == "SELECT") {
                            if (typeof form_json_data.form_json["" + data_obj_id].defaultValues != "undefined") {
                                $.each(form_json_data.form_json["" + data_obj_id].defaultValues, function(index, item) {
                                    var select_strval = form_json_data.form_json["" + data_obj_id].defaultValues[index];
                                    if ($(the_field).children("option").eq(index).length >= 1 && $(the_field).children("option").eq(index).val() == select_strval) {
                                        $(the_field).children("option").eq(index).prop("selected", true);
                                    }
                                });
                            }
                        } else {
                            if ($(this).find(".getFields_" + data_obj_id).attr("default-type")) {
                                if ($(this).find(".getFields_" + data_obj_id).attr("default-type") == "static") {
									if( typeof $(this).find(".getFields_" + data_obj_id).attr("default-static-value") != "undefined"){
										if($(this).find(".getFields_" + data_obj_id).attr("default-static-value").length >= 1){
											//console.log($(this).find(".getFields_" + data_obj_id).attr("name"))
											$(this).find(".getFields_" + data_obj_id).val($(this).find(".getFields_" + data_obj_id).attr("default-static-value"));
										}
									}
                                } else if ($(this).find(".getFields_" + data_obj_id).attr("default-type") == "computed") {
                                    defaultComputed(data_obj_id, the_field, this, "startUpDefaultValComputed");
                                }
                            }
                        }
                    }
                    // }catch(error){
                    //    console.log("ERROR on getting the json datas of this individual field");
                    //    console.log("OR the json variable form_json_data.form_json[''+"+data_obj_id+"] is not existing this id:->["+data_obj_id+"]");
                    //    console.log("OR the values of computed is not well defined");
                    //    console.log(error)
                    // }
					// console.log($('[name="Date_Hired"]').val())
					// console.log($(this).find(".getFields_" + data_obj_id).attr("name"))
					// console.log($(this).find(".getFields_" + data_obj_id).attr("default-computed-value"))
                });
                // $('[default-type="computed"][default-formula-value]').change();

            }
        } else {
            console.log("form_json_data is undefined");
        }

        //removing unnecessary ui for request client side
        if ($(".setObject-drag-handle").length >= 1) {
            $(".setObject-drag-handle").remove();
        }
        if ($(".setObjects_actions").length >= 1) {
            $(".setObjects_actions").remove();
        }
        if ($(".form-builder-ruler").length >= 1) {
            $(".form-builder-ruler").remove();
        }
        if ($(".ui-resizable").length >= 1) {
            $(".ui-resizable").removeClass("ui-resizable");
        }
        if ($(".ui-droppable").length >= 1) {
            $(".ui-droppable").removeClass("ui-droppable");
        }
        if ($(".ui-draggable").length >= 1) {
            $(".ui-draggable").removeClass("ui-draggable");
        }
        if ($(".ui-resizable-handle").length >= 1) {
            $(".ui-resizable-handle").remove();
        }
        if($(".component-ancillary-focus").length >= 1){
            $(".component-ancillary-focus").removeClass("component-ancillary-focus");
        }
        if($(".component-primary-focus").length >= 1){
            $(".component-primary-focus").removeClass("component-primary-focus");
        }
        if ($(".form-tabbable-pane").length >= 1) {
            $(".form-tabbable-pane").each(function() {
                $(this).children('.ui-tabs-nav[role="tablist"]').find(".ui-icon-close").hide();
            });
        }
        if($(".form-table[border-visible='No']").length >= 1 ){
            var ele_style_table = $(
                "<style>"+
                ".form-table[border-visible='No'] td{"+
                    "border: none;"+
                "}"+
                "</stlyle>"
            );
            $("body").prepend(ele_style_table);
        }
        if ($('input[data-type="dateTime"]').length >= 1) {

            var disabledDays = [];
            $('input[data-type="dateTime"]').datetimepicker({
                dateFormat: 'yy-mm-dd',
                beforeShowDay: function(date) {
                    //console.log(this);
                    var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
                    for (i = 0; i < disabledDays.length; i++) {
                        if ($.inArray((m + 1) + '-' + d + '-' + y, disabledDays) != -1) {
                            return [false, 'red', 'This is Holiday'];
                        }
                    }
                    return [true];
                }
            });
            if ($('input[data-type="dateTime"]').val().length >= 1) {
                // replace value of date pickers
                $('input[data-type="dateTime"]').each(function() {
                    $(this).val(ThisDate($(this).val()).formatDate("Y-m-d H:i"));
                });
            }
        }
        if ($('input[data-type="date"]').length >= 1) {
            $('input[data-type="date"]').datepicker({
                'dateFormat': 'yy-mm-dd'
            });
            if ($('input[data-type="date"]').val().length >= 1) {
                // replace value of date pickers
                $('input[data-type="date"]').each(function() {
                    $(this).val(ThisDate($(this).val()).formatDate("Y-m-d"));
                });
            }
        }
		if ($('input[data-type="time"]').length >= 1) {
            $('input[data-type="time"]').datetimepicker({                   
				dateFormat: '', 
				timeFormat: 'HH:mm', 
				timeOnly: true                                   
			 }); 
            //if ($('input[data-type="time"]').val().length >= 1) {
                // replace value of date pickers
               // $('input[data-type="time"]').each(function() {
                    //$(this).val(ThisDate($(this).val()).formatDate("Y-m-d"));
                //});
            //}
        }
        if ($('textarea.form-textarea.getFields[data-type="longtext"]').length >= 1) {
            $('textarea.form-textarea.getFields[data-type="longtext"]').css({
                "resize": "none"
            });
        }
        if ($(".form-tabbable-pane").length >= 1) {
            $(".form-tabbable-pane").each(function(eqi_ftp) {
                $(this).find(".ui-state-active").removeClass("ui-state-active");
                $(this).tabPanel({
                    //resizableContent:true,
                    //resizableContentContainment:".preview_content"
                });
            });
            $(".edit-title-tab-panel").remove();
            $(".li-add-new-tab-panel").remove();
        }

        if ($(".form-table").length >= 1) {
            $(".form-table").each(function() {
                if ($(this).closest(".table-wrapper").length >= 1) {
                    $(this).closest(".table-wrapper").find(".table-actions-ra").remove();
                    if ($(this).closest(".table-wrapper").find(".ui-resizable-handle").length >= 1) {
                        $(this).closest(".table-wrapper").find(".ui-resizable-handle").remove();
                    }
                } else if ($(this).find(".table-actions-ra").length >= 1) {
                    $(this).find(".table-actions-ra").remove();
                    if ($(this).find(".ui-resizable-handle").length >= 1) {
                        $(this).find(".ui-resizable-handle").remove();
                    }
                }

                if ($(this).attr("repeater-table")) {
                    if ($(this).attr("repeater-table") == "true") {
                        // $(this).closest(".")//DITO NA AKO
                        makeRepeaterTable($(this), function(table_ui) {
                            $(table_ui).children("tbody").children("tr").on({
                                "mouseenter": function(e) {
                                    $(this).children("td").children(".td-relative").children(".repeater-action").not(".disable-repeater-action").stop(false, false).animate({
                                        "opacity": 1
                                    }, 500);
                                },
                                "mouseleave": function(e) {
                                    $(this).children("td").children(".td-relative").children(".repeater-action").not(".disable-repeater-action").stop(false, false).animate({
                                        "opacity": 0
                                    }, 500);
                                }
                            });
                            $(table_ui).children("tbody").children("tr").find(".disable-repeater-action").css("display", "none");
                        });
                        var object_field_ele = $(this).closest(".setOBJ").find("#obj_fields_" + $(this).closest(".setOBJ").attr("data-object-id"));
                        // object_field_ele.css({
                        //   "width":(object_field_ele.outerWidth())+"px",
                        //   "height":(object_field_ele.outerHeight())+"px",
                        //   "overflow":"auto"
                        // });
                        // object_field_ele.children(".table-wrapper").css({
                        //   "margin-left":"40px"
                        // })
                        object_field_ele.css({
                            "overflow": "auto"
                        });
                    }
                }

                $(this).closest(".setOBJ").css({"height": ($(this).closest(".setOBJ").height()) + "px"})
                if ($(this).closest(".setOBJ").css("display") == "none") {
                } else {
                    $(this).closest(".setOBJ").css({"display": "block"})
                }


            });
        }
        if($(".getFields[data-input-type='Currency']").length >= 1){
            $(".getFields[data-input-type='Currency']").each(function(){
                $(this).on("change.currency_format",function(){
                    if($.isNumeric($(this).val())){
                        var value_number = parseFloat($(this).val());
                        $(this).val(value_number.currencyFormat());
                    }else{
                        var value_nito = $(this).val()
                        var sanitized_val = value_nito.replace(/[\s,]/g,"");
                        if($.isNumeric(sanitized_val)){
                            var value_number = parseFloat(sanitized_val);
                            $(this).val(value_number.currencyFormat());
                        }
                    }
                })
            });
            $(".getFields[data-input-type='Currency']").change();
        }


        $('[tabindex="1"]').eq(0).focus();
        var pathname = window.location;
        if (getParametersName("view_type", pathname) == "update") {
            adjustComponentBelowV2.collectObjects();
        }
        
        repeater.setData();

        if (getParametersName("view_type", pathname) == "update") {

            adjustComponentBelowV2.adjustElements();
            $(".repeater-action").css("display", "none");
            $(".getFields").prop("disabled", true);
        }
        
        //work around
        $(".getFields").each(function() {
            if ($.trim($(this).val()) == "null" || $.trim($(this).val()) == "Invalid Date") {
                $(this).val("");
            }
        })
        // $('[default-type="computed"][default-formula-value]').change();

        //triggering the change after initialization...
        $(".getFields").each(function() {
            var this_element = $(this);
            if (typeof this_element.data("events") !== "undefined") {
                if (typeof this_element.data("events").change != "undefined") {
                    if (this_element.data("events").change.length >= 1) {
                        this_element.change();
                    }
                }
            }
        });

        computeVisibility();
    });


    function StrLeft(str_val, str_length) {
        var str_to_process = String(str_val);
        return str_to_process.substr(0, str_length);
    }
    function StrRight(str_val, str_length) {
        var str_to_process = String(str_val);
        var start = (str_to_process.length - (str_length));
        if (start <= -1) {
            start = 0;
        }
        return str_to_process.substr(start, str_length);
    }
    function StrCount(str_val) {
        if (typeof str_val != "undefined") {
            return String(str_val).length;
        }
    }
    function StrConcat(){
        var args = arguments;//infinite argument
        var collect_strings = "";
        for(var ctr = 0 ; ctr < args.length ; ctr++){
            collect_strings = collect_strings + args[ctr];
        }
        return collect_strings;
    }
    function StrGet(str_val, str_istart, str_char_len) {
        if (typeof str_val == "undefined") {
            return "";
        }
        var string_val = String(str_val);
        var string_start_index = Number(str_istart);
        if (string_start_index <= 0) {
            return "";
        }
        if (typeof str_char_len == "undefined") {
            return String(string_val.charAt((Number(str_istart) - 1)));
        } else {
            return string_val.substr((Number(str_istart) - 1), Number(str_char_len));
        }
    }
    function printAllExistingFormulas() {
        var collect_in_json = [];
        $('[default-formula-value][default-type="computed"]').each(function() {
            collect_in_json.push({
                "this_ele_formula": $(this).attr("default-formula-value"),
                "this_ele": $(this),
                "object_id": $(this).closest(".setOBJ").attr("data-object-id")
            })
            console.log($(this).attr("default-formula-value"));
        })
        console.log("===========================================");
        console.log("check DOM here below!");
        return collect_in_json;
    }

    function SDev(fieldname){
        var fn_str = fieldname;
        var nums = [];
        nums.push(Number($('[name="'+fn_str+'"]').val()))
        
        $('[rep-original-name="'+fn_str+'"]').each(function(){
            nums.push(Number($(this).val()));
        });

        var dataSD = {};
        var mean = 0;
        var mean_average = 0;
        var decimal = 1000000;
        
        dataSD.totalNumbers = nums.length;
        
        function getMean(nums){
            for(var ii in nums){
                mean = mean + parseFloat(nums[ii]);
            }
            mean = mean/nums.length;
            mean_average = Math.round(mean*decimal)/decimal;
            return Math.round(mean*decimal)/decimal;
        }
        dataSD.meanAverage = getMean(nums);
        
        var variance = 0;
        var varian = 0;
        
        function getVariance(nums){
            for(var ii in nums){
                variance = variance + Math.pow( (parseFloat(nums[ii]) - mean ) , 2 );
            }
            varian = variance/(nums.length - 1);
            varian = (isNaN(varian) == false)?varian:0;
            return Math.round(varian*decimal)/decimal;
        }
        dataSD.varianceSD = getVariance(nums);
        
        var sd = 0;
        
        function getStandardDeviation(){
            sd = Math.sqrt(varian);
            return Math.round(sd*decimal)/decimal;
        }
        dataSD.standardDeviation = getStandardDeviation();
        var pop = 0;
        
        function getPopulationSD(nums){
            pop = variance/nums.length;
            pop_sqrt = Math.sqrt(pop);
            return Math.round(pop_sqrt*decimal)/decimal;
        }
        dataSD.populationSD = getPopulationSD(nums);
        
        var var_pop = 0;
        
        function getVariancePSD(nums){
            var_pop = variance/nums.length;
            return Math.round(var_pop*decimal)/decimal;
        }
        dataSD.variancePSD = getVariancePSD(nums);
        return dataSD["standardDeviation"];
    }
    function Sum(sum_fn) {
        var fieldname = sum_fn;
        var summation = 0;
        if (fieldname.indexOf("@") >= 0) {
            fieldname = fieldname.replace("@", "");
        }
        summation = summation + Number($('[name="' + fieldname + '"]').val().replace(/,/g,""));

        $('[rep-original-name="' + fieldname + '"]').each(function(eqi) {
            summation = summation + Number($(this).val().replace(/,/g,""));
        });

        return summation;
    }

    function GetMax(fns) {
        var fieldname = fns;
        var collect_values = [];
        if (fieldname.indexOf("@") >= 0) {
            fieldname = fieldname.replace("@", "");
        }
        collect_values.push(Number($('[name="' + fieldname + '"]').val()));

        $('[rep-original-name="' + fieldname + '"]').each(function(eqi) {
            collect_values.push(Number($(this).val()));
        });
        if (collect_values.length == 0) {
            return "";
        } else {
            return (collect_values.sort(function(a, b) {
                return b - a
            }))[0];
        }
    }
    function GetAVG(fns){
        var fieldname = "@"+fns;
        var collect_values = [];
        var totality = 0;
        var counted_names = 0;
		//console.log('asd',fieldname)
        if (fieldname.indexOf("@") >= 0) {
            fieldname = fieldname.replace("@", "");
            totality = totality + Number($('[name="' + fieldname + '"]').val());
            counted_names++;
            $('[rep-original-name="' + fieldname + '"]').each(function(eqi) {
                totality = totality + Number($(this).val());
                counted_names++;
            });
            if(counted_names == 0){
                return 0;
            }else{
                return (totality/counted_names);
            }
        }else{

        }
    }
    function GetMin(fns) {
        var fieldname = fns;
        var collect_values = [];
        if (fieldname.indexOf("@") >= 0) {
            fieldname = fieldname.replace("@", "");
        }
        collect_values.push(Number($('[name="' + fieldname + '"]').val()));

        $('[rep-original-name="' + fieldname + '"]').each(function(eqi) {
            collect_values.push(Number($(this).val()));
        });

        if (collect_values.length == 0) {
            return "";
        } else {
            return (collect_values.sort(function(a, b) {
                return a - b
            }))[0];
        }
    }
    function CountDayIf(start_date, end_date) {
        var args = arguments;
        var starting_date = new Date(start_date);

        var ending_date = new Date(end_date);
        var counted_if_days = 0;
        if (typeof args[2] !== "undefined") {
            var days_difference = starting_date.diffDaysIn(ending_date);
            for (var ii = 0; ii <= days_difference; ii++) {
                if(ii == 0){
                    var adjusted_day = starting_date.adjustDay(0).formatDate('l');
                }else{
                    var adjusted_day = starting_date.adjustDay(+1).formatDate('l');
                }
                // console.log(ii,adjusted_day,starting_date)
                for (var ca = 0; ca < args.length; ca++) {
                    var param_day = args[ca];
                    if ( ( adjusted_day == param_day && ca >= 2 ) != false ) {
                        
                        // console.log(adjusted_day+" == "+param_day+" && "+ca+" >= "+2+"\n",(( adjusted_day == param_day && ca >= 2 ) != false ))
                        counted_if_days++;
                    }
                }
            }
            return counted_if_days;
        }
    }
    function getFieldVal(field){
        var form_fn_obj = $(field);
        var form_field_name = form_fn_obj.attr("name");
        var collected_values_arr = [];
        if(typeof form_fn_obj.attr("type") != "undefined"){
            if(form_fn_obj.attr("type") == "radio"){
                $('[name="'+form_field_name+'"]:checked').each(function(){
                    collected_values_arr.push($(this).val())
                })
            }else if(form_fn_obj.attr("type") == "checkbox"){
                $('[name="'+form_field_name+'"]:checked').each(function(){
                    collected_values_arr.push($(this).val())
                })
            }else{

            }
        }else{

        }
    }
    function ThisDate(this_date) {
        var this_time = new Date(this_date);
        if(this_time == "Invalid Date"){
            return this_time;
        }else{
            var formatted_pdate = this_time.formatDate('Y-m-d H:i:s');
            this_time = formatted_pdate.match(/..:..:..\s[A-Za-z]{2}|..:..\s[A-Za-z]{2}|..:..:..|..:../g);
        }
        
        if(this_time != null){
            var this_time2 = this_time[0].replace(/\s[A-Za-z]{2}/g,"");
            var this_time_splitted = this_time2.split(":");
            var time_hours = "";
            var time_minutes = "";
            var time_seconds = "";

            if(typeof this_time_splitted[0] != "undefined"){ //hours
                time_hours = this_time_splitted[0];
            }
            if(typeof this_time_splitted[1] != "undefined"){ //minutes
                time_minutes = this_time_splitted[1];
            }
            var dis_date = this_date.toString().replace(this_time[0],"");
            var this_new_date = new Date($.trim(dis_date));

            this_new_date = new Date(this_new_date.setHours(time_hours));

            this_new_date = new Date(this_new_date.setMinutes(time_minutes));
        }else{
            var this_new_date = new Date(this_date);
        }
        // var converted_date = (this_new_date.getFullYear())+"-"+(this_new_date.getMonth()+1)+"-"+(this_new_date.getDate());
        if (this_new_date == "Invalid Date") {
            return this_new_date;
        } else {
            return this_new_date;
        }
    }
    Number.prototype.currencyFormat = function(){
       // (?<=\d)(?=(\d\d\d)+(?!\d))
       // return this.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
       // console.log(this)
       // console.log("ow")
       var negative_pad = "";
       var float_value = "";
       var integer = "";
       if(this < 0){
            negative_pad = "-";
            float_value = this.toString().split(".");
            integer = float_value[0].replace("-","");
       }else{
            float_value = this.toString().split(".");
            integer = float_value[0];
       }
       
       var decimal = "";
       if(float_value.length == 2){
            decimal = float_value[1];
            integer = negative_pad+integer.split(/(?=(?:...)*$)/).join(",");
            return integer+"."+decimal;
       }else{
            integer = negative_pad+integer.split(/(?=(?:...)*$)/).join(",");
            return integer+".00";
       }
    };
    Date.prototype.formatDate = function(format) {
        if (this == "Invalid Date") {
            return this;
        } else {
            timestamp = this;
            // http://kevin.vanzonneveld.net
            // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
            // +      parts by: Peter-Paul Koch (http://www.quirksmode.org/js/beat.html)
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: MeEtc (http://yass.meetcweb.com)
            // +   improved by: Brad Touesnard
            // +   improved by: Tim Wiel
            // +   improved by: Bryan Elliott
            // +   improved by: David Randall
            // +      input by: Brett Zamir (http://brett-zamir.me)
            // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: Theriault
            // +  derived from: gettimeofday
            // +      input by: majak
            // +   bugfixed by: majak
            // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +      input by: Alex
            // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
            // +   improved by: Theriault
            // +   improved by: Brett Zamir (http://brett-zamir.me)
            // +   improved by: Theriault
            // +   improved by: Thomas Beaucourt (http://www.webapp.fr)
            // +   improved by: JT
            // +   improved by: Theriault
            // +   improved by: Rafał Kukawski (http://blog.kukawski.pl)
            // +   bugfixed by: omid (http://phpjs.org/functions/380:380#comment_137122)
            // +      input by: Martin
            // +      input by: Alex Wilson
            // +      input by: Haravikk
            // +   improved by: Theriault
            // +   bugfixed by: Chris (http://www.devotis.nl/)
            // %        note 1: Uses global: php_js to store the default timezone
            // %        note 2: Although the function potentially allows timezone info (see notes), it currently does not set
            // %        note 2: per a timezone specified by date_default_timezone_set(). Implementers might use
            // %        note 2: this.php_js.currentTimezoneOffset and this.php_js.currentTimezoneDST set by that function
            // %        note 2: in order to adjust the dates in this function (or our other date functions!) accordingly
            // *     example 1: date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h',  );
            // *     returns 1: '09:09:40 m is month'
            // *     example 2: date('F j, Y, g:i a', 1062462400);
            // *     returns 2: 'September 2, 2003, 2:26 am'
            // *     example 3: date('Y W o', 1062462400);
            // *     returns 3: '2003 36 2003'
            // *     example 4: x = date('Y m d', (new Date()).getTime()/1000);
            // *     example 4: (x+'').length == 10 // 2009 01 09
            // *     returns 4: true
            // *     example 5: date('W', 1104534000);
            // *     returns 5: '53'
            // *     example 6: date('B t', 1104534000);
            // *     returns 6: '999 31'
            // *     example 7: date('W U', 1293750000.82); // 2010-12-31
            // *     returns 7: '52 1293750000'
            // *     example 8: date('W', 1293836400); // 2011-01-01
            // *     returns 8: '52'
            // *     example 9: date('W Y-m-d', 1293974054); // 2011-01-02
            // *     returns 9: '52 2011-01-02'
            var that = this,
                    jsdate,
                    f,
                    // Keep this here (works, but for code commented-out
                    // below for file size reasons)
                    //, tal= [],
                    txt_words = ["Sun", "Mon", "Tues", "Wednes", "Thurs", "Fri", "Satur", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                    // trailing backslash -> (dropped)
                    // a backslash followed by any character (including backslash) -> the character
                    // empty string -> empty string
                    formatChr = /\\?(.?)/gi,
                    formatChrCb = function(t, s) {
                        return f[t] ? f[t]() : s;
                    },
                    _pad = function(n, c) {
                        n = String(n);
                        while (n.length < c) {
                            n = '0' + n;
                        }
                        return n;
                    };
            f = {
                // Day
                d: function() { // Day of month w/leading 0; 01..31
                    return _pad(f.j(), 2);
                },
                D: function() { // Shorthand day name; Mon...Sun
                    return f.l().slice(0, 3);
                },
                j: function() { // Day of month; 1..31
                    return jsdate.getDate();
                },
                l: function() { // Full day name; Monday...Sunday
                    return txt_words[f.w()] + 'day';
                },
                N: function() { // ISO-8601 day of week; 1[Mon]..7[Sun]
                    return f.w() || 7;
                },
                S: function() { // Ordinal suffix for day of month; st, nd, rd, th
                    var j = f.j(),
                            i = j % 10;
                    if (i <= 3 && parseInt((j % 100) / 10, 10) == 1) {
                        i = 0;
                    }
                    return ['st', 'nd', 'rd'][i - 1] || 'th';
                },
                w: function() { // Day of week; 0[Sun]..6[Sat]
                    return jsdate.getDay();
                },
                z: function() { // Day of year; 0..365
                    var a = new Date(f.Y(), f.n() - 1, f.j()),
                            b = new Date(f.Y(), 0, 1);
                    return Math.round((a - b) / 864e5);
                },
                // Week
                W: function() { // ISO-8601 week number
                    var a = new Date(f.Y(), f.n() - 1, f.j() - f.N() + 3),
                            b = new Date(a.getFullYear(), 0, 4);
                    return _pad(1 + Math.round((a - b) / 864e5 / 7), 2);
                },
                // Month
                F: function() { // Full month name; January...December
                    return txt_words[6 + f.n()];
                },
                m: function() { // Month w/leading 0; 01...12
                    return _pad(f.n(), 2);
                },
                M: function() { // Shorthand month name; Jan...Dec
                    return f.F().slice(0, 3);
                },
                n: function() { // Month; 1...12
                    return jsdate.getMonth() + 1;
                },
                t: function() { // Days in month; 28...31
                    return (new Date(f.Y(), f.n(), 0)).getDate();
                },
                // Year
                L: function() { // Is leap year?; 0 or 1
                    var j = f.Y();
                    return j % 4 === 0 & j % 100 !== 0 | j % 400 === 0;
                },
                o: function() { // ISO-8601 year
                    var n = f.n(),
                            W = f.W(),
                            Y = f.Y();
                    return Y + (n === 12 && W < 9 ? 1 : n === 1 && W > 9 ? -1 : 0);
                },
                Y: function() { // Full year; e.g. 1980...2010
                    return jsdate.getFullYear();
                },
                y: function() { // Last two digits of year; 00...99
                    return f.Y().toString().slice(-2);
                },
                // Time
                a: function() { // am or pm
                    return jsdate.getHours() > 11 ? "pm" : "am";
                },
                A: function() { // AM or PM
                    return f.a().toUpperCase();
                },
                B: function() { // Swatch Internet time; 000..999
                    var H = jsdate.getUTCHours() * 36e2,
                            // Hours
                            i = jsdate.getUTCMinutes() * 60,
                            // Minutes
                            s = jsdate.getUTCSeconds(); // Seconds
                    return _pad(Math.floor((H + i + s + 36e2) / 86.4) % 1e3, 3);
                },
                g: function() { // 12-Hours; 1..12
                    return f.G() % 12 || 12;
                },
                G: function() { // 24-Hours; 0..23
                    return jsdate.getHours();
                },
                h: function() { // 12-Hours w/leading 0; 01..12
                    return _pad(f.g(), 2);
                },
                H: function() { // 24-Hours w/leading 0; 00..23
                    return _pad(f.G(), 2);
                },
                i: function() { // Minutes w/leading 0; 00..59
                    return _pad(jsdate.getMinutes(), 2);
                },
                s: function() { // Seconds w/leading 0; 00..59
                    return _pad(jsdate.getSeconds(), 2);
                },
                u: function() { // Microseconds; 000000-999000
                    return _pad(jsdate.getMilliseconds() * 1000, 6);
                },
                // Timezone
                e: function() { // Timezone identifier; e.g. Atlantic/Azores, ...
                    // The following works, but requires inclusion of the very large
                    // timezone_abbreviations_list() function.

                    throw 'Not supported (see source code of date() for timezone on how to add support)';
                },
                I: function() { // DST observed?; 0 or 1
                    // Compares Jan 1 minus Jan 1 UTC to Jul 1 minus Jul 1 UTC.
                    // If they are not equal, then DST is observed.
                    var a = new Date(f.Y(), 0),
                            // Jan 1
                            c = Date.UTC(f.Y(), 0),
                            // Jan 1 UTC
                            b = new Date(f.Y(), 6),
                            // Jul 1
                            d = Date.UTC(f.Y(), 6); // Jul 1 UTC
                    return ((a - c) !== (b - d)) ? 1 : 0;
                },
                O: function() { // Difference to GMT in hour format; e.g. +0200
                    var tzo = jsdate.getTimezoneOffset(),
                            a = Math.abs(tzo);
                    return (tzo > 0 ? "-" : "+") + _pad(Math.floor(a / 60) * 100 + a % 60, 4);
                },
                P: function() { // Difference to GMT w/colon; e.g. +02:00
                    var O = f.O();
                    return (O.substr(0, 3) + ":" + O.substr(3, 2));
                },
                T: function() { // Timezone abbreviation; e.g. EST, MDT, ...
                    // The following works, but requires inclusion of the very
                    // large timezone_abbreviations_list() function.

                    return 'UTC';
                },
                Z: function() { // Timezone offset in seconds (-43200...50400)
                    return -jsdate.getTimezoneOffset() * 60;
                },
                // Full Date/Time
                c: function() { // ISO-8601 date.
                    return 'Y-m-d\\TH:i:sP'.replace(formatChr, formatChrCb);
                },
                r: function() { // RFC 2822
                    return 'D, d M Y H:i:s O'.replace(formatChr, formatChrCb);
                },
                U: function() { // Seconds since UNIX epoch
                    return jsdate / 1000 | 0;
                }
            };
            this.date = function(format, timestamp) {
                that = this;
                jsdate = (timestamp === undefined ? new Date() : // Not provided
                        (timestamp instanceof Date) ? new Date(timestamp) : // JS Date()
                        new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int)
                        );
                return format.replace(formatChr, formatChrCb);
            };
            return this.date(format, timestamp);
        }//end of if
    }
    Date.prototype.diffHoursIn = function(date2){
       // / 1000 / 60 / 60
        if (typeof date2 != "undefined" && this != "Invalid Date") {
            var date2_dt_obj = new Date(date2);
            var t2 = date2_dt_obj.getTime();
            var t1 = this.getTime();
            return Math.abs( ( t1 - t2 ) / 1000 / 60 / 60 );
        } else {
            return "";
        }
    }
    Date.prototype.diffDaysIn = function(date2) {
        if (typeof date2 != "undefined" && this != "Invalid Date") {
            var date2_dt_obj = new Date(date2);
            var t2 = date2_dt_obj.getTime();
            var t1 = this.getTime();
            return Math.abs(parseInt((t1 - t2) / (24 * 3600 * 1000),10) );
        } else {
            return "";
        }
    }
    Date.prototype.diffWeeksIn = function(date2) {
        if (typeof date2 != "undefined" && date2.length >= 1 && this != "Invalid Date") {
            var date2_dt_obj = new Date(date2);
            var t2 = date2_dt_obj.getTime();
            var t1 = this.getTime();

            return Math.abs(parseInt((t1 - t2) / (24 * 3600 * 1000 * 7)));
        } else {
            return "";
        }
    }
    Date.prototype.diffMonthsIn = function(date2) {
        if (typeof date2 != "undefined" && date2.length >= 1 && this != "Invalid Date") {
            var date2_dt_obj = new Date(date2);
            var d1Y = this.getFullYear();
            var d2Y = date2_dt_obj.getFullYear();
            var d1M = this.getMonth();
            var d2M = date2_dt_obj.getMonth();
            return Math.abs((d2M + 12 * d2Y) - (d1M + 12 * d1Y));
        } else {
            return "";
        }
    }

    Date.prototype.diffYearsIn = function(date2) {
        if (typeof date2 != "undefined" && date2.length >= 1 && this != "Invalid Date") {
            var date2_dt_obj = new Date(date2);
            return Math.abs(date2_dt_obj.getFullYear() - this.getFullYear());
        } else {
            return "";
        }
    }

    Date.prototype.adjustSeconds = function(value) {
        if ($.isNumeric(value)) {
            var new_date = this.setSeconds(parseInt(this.getSeconds()) + parseInt(value));
            var obj_new_date = new Date(new_date);
            return obj_new_date;
        } else {
            return "";
        }
    }
    Date.prototype.adjustMinutes = function(value) {
        if ($.isNumeric(value)) {
            var new_date = this.setMinutes(parseInt(this.getMinutes()) + parseInt(value));
            var obj_new_date = new Date(new_date);
            return obj_new_date;
        } else {
            return "";
        }
    }
    Date.prototype.adjustHours = function(value) {
        if ($.isNumeric(value)) {
            var new_date = this.setHours(parseInt(this.getHours()) + parseInt(value));
            var obj_new_date = new Date(new_date);
            return obj_new_date;
        } else {
            return "";
        }
    }
    Date.prototype.adjustDay = function(value) {
        if ($.isNumeric(value)) {
            var new_date = this.setDate(parseInt(this.getDate()) + parseInt(value));
            var obj_new_date = new Date(new_date);
            return obj_new_date;
        } else {
            return "";
        }
    }
    Date.prototype.adjustMonth = function(value) {
        if ($.isNumeric(value)) {
            var new_date = this.setMonth(parseInt(this.getMonth()) + parseInt(value));
            var obj_new_date = new Date(new_date);
            return obj_new_date;
        } else {
            return "";
        }
    }
    Date.prototype.adjustYear = function(value) {
        if ($.isNumeric(value)) {
            var new_date = this.setFullYear(parseInt(this.getFullYear()) + parseInt(value));
            var obj_new_date = new Date(new_date);
            return obj_new_date;
        } else {
            return "";
        }
    }

    function GivenIf(condition, valueTrue, valueFalse) {
        try {
            //splitted_condition_val = condition.split(/<=|>=|==|!=|<|>|\(|\)|!/g);
            if (eval(condition)) {
                return valueTrue;
            } else {
                return valueFalse;
            }
        } catch (error) {
            return "Conditional Error!";
        }
    }
    function Concat() {
        try {
            var collect_strings = "";
            for (var ctr = 0; ctr < arguments.length; ctr++) {
                //
                collect_strings += arguments[ctr];
            }
            return collect_strings;
        } catch (error) {
            console.log("ERROR ON USAGE OF CONCATENATION");
        }
    }
    function GetRound(given_num,decimal_digit){
        var decimal_places = "1";
        for(var ii = 1 ; ii <= decimal_digit ; ii++){
            decimal_places += ""+"0";
        }
        decimal_places = Number(decimal_places);
        return Math.round(given_num * decimal_places) / decimal_places;
    }

    function collectNamesOnForm() {
        $(".frmrequest").find(".setOBJ").each(function() {
            //
        });
    }





    function makeRepeaterTable(tableElement, callBack) {
        try {
            if (typeof callBack == "undefined") {
                //do nothing just catch errs
            }
        } catch (errs) {
            console.log(errs)
        }

        var repeat_fields = ".setObject";
        var table_body = $(tableElement).children("tbody");
        var table_row = table_body.children("tr");
        //MAG LALAGAY MUNA NG BUTTON ADDING SA BAWAT ROW
        //at initial startup
        //adding buttons
        table_row.each(function(eqi_tr) {
            td_ele = $(this).children("td");
            // relative_content = td_ele.last()/*.eq(0)*/.children(".td-relative");
            relative_content = td_ele.eq(0).children(".td-relative");
            $(this).addClass("original-row"); //declaring original row
            $(this).children("td").attr("row-height", $(this).outerHeight());
            relative_content.append(adding_and_removing_btn = $(
                    '<span class="repeater-action" style="opacity:0;z-index:2;position:absolute;bottom:0px;">' +
                    '<a class="icon-plus rep-add-spec-row" style="width:20px;height:20px;padding:5px;"></a>' +
                    '<a class="icon-minus rep-remove-spec-row" style="width:20px;height:20px;padding:5px;"></a>' +
                    '</span>'
                    ));
            //don't display remove row on original buttons
            adding_and_removing_btn.children(".rep-remove-spec-row").eq(0).css({
                "display": "none"
            });
            // adding_and_removing_btn.css({
            //    // "margin-left":"-"+(adding_and_removing_btn.css("width")),
            //    "margin-right":"-"+(adding_and_removing_btn.css("width")),
            //    "position":"absolute",
            //    "right":"0px"
            // });
            adding_and_removing_btn.css({
                // "margin-left":"-"+(adding_and_removing_btn.css("width")),
                "left": "0px"
            });
            //adding events for button
            evRepeaterAdd(adding_and_removing_btn);
            evRepeaterRemove(adding_and_removing_btn);
            
            //adding events for button version 2
            // evRepeaterAddV2(adding_and_removing_btn);
            // evRepeaterRemoveV2(adding_and_removing_btn);
        });

        //functionality event
        {//OLD VERSION SLOW
            function evRepeaterAdd(repeaterBtnEle) {
                if (repeaterBtnEle.children(".rep-add-spec-row").length >= 1) {
                    repeaterBtnEle.children(".rep-add-spec-row").on({
                        "click": function(e) {
                            var select_dis_table = $(this).parents("table.form-table");
                            if(select_dis_table.data("added_rows_uid")){
                                select_dis_table.data("added_rows_uid",(select_dis_table.data("added_rows_uid")+1) );
                            }else{
                                select_dis_table.data("added_rows_uid",1);
                            }
                            e.preventDefault();
                            var pathname = window.location;

                            if ($(this).closest("tr.original-row").length >= 1) {
                                //repeat clicked row, append content
                                var appended_row = "";
                                $(this).closest("tr.original-row").after(appended_row = $(
                                    '<tr>' +
                                        $(this).closest("tr.original-row").html() +
                                    '</tr>'
                                ));
                                appended_row.children("td").slideUp(500).stop(true, true);
                                appended_row.children("td").slideDown(500);
                                var rep_btn_container_ar = appended_row.children("td").children(".td-relative").children(".repeater-action");
                                //display the remove row button of the repeated row
                                rep_btn_container_ar.children(".rep-remove-spec-row").css({
                                    "display": ""
                                });
                                rep_btn_container_ar.css({
                                    "left": "0px"
                                });


                                //adding event for original row button

                                evRepeaterAdd(rep_btn_container_ar);
                                evRepeaterRemove(rep_btn_container_ar);
                                // rebindFieldFunctionality(appended_row);
                                rebindFieldFunctionalityV3(appended_row);
                            } else {
                                //repeat clicked row, append content
                                var appended_row = "";
                                $(this).closest("tr").after(appended_row = $(
                                    '<tr>' +
                                        $(this).closest("tr").html() +
                                    '</tr>'
                                ));
                                appended_row.children("td").slideUp(500).stop(true, true);
                                appended_row.children("td").slideDown(500);
                                var rep_btn_container_ar2 = appended_row.children("td").children(".td-relative").children(".repeater-action");
                                //display the remove row button of the repeated row
                                rep_btn_container_ar2.children(".rep-remove-spec-row").css({
                                    "display": ""
                                });
                                rep_btn_container_ar2.css({
                                    // "margin-left":"-"+(rep_btn_container_ar2.css("width")),
                                    "left": "0px"
                                });

                                //adding event for original row button
                                evRepeaterAdd(rep_btn_container_ar2);
                                evRepeaterRemove(rep_btn_container_ar2);
                                // rebindFieldFunctionality(appended_row);
                                rebindFieldFunctionalityV3(appended_row);
                            }
                            // refreshRepeaterTable($(this).closest(".form-table"));
                            // rebindFieldFunctionality(appended_row); // MAY PROBLEMS PA SA NAMES BIND
                            // rebindFieldFunctionalityV2($(this).closest(".form-table"));
                            
                            return false;
                        }
                    });
                }
            }
            function rebindFieldFunctionality(appended_row) { // defaultComputed(data_obj_id,the_field_ele,this_element,eventAddressNamespace){
                if (appended_row.find(".hasDatepicker").length >= 1) {
                    appended_row.find(".hasDatepicker").each(function() {
                        $(this).removeClass("hasDatepicker");
                        if ($(this).attr("data-type")) {
                            if ($(this).attr("data-type") == "date") {
                                $(this).datepicker({
                                    'dateFormat': 'yy-mm-dd'
                                });

                            } else if ($(this).attr("data-type") == "dateTime") {
                                $(this).datetimepicker({
                                    'dateFormat': 'yy-mm-dd'
                                });
                            }
                        }
                    });
                }
                appended_row.find(".setObject").each(function() {

                });
            }
            function rebindFieldFunctionalityV2(table) {
                var table_id = table.closest(".setOBJ").attr("data-object-id");
                table.find(".hasDatepicker").each(function(eqi) {
                    // console.log($(this).data())
                    // console.log(typeof $(this).data().datepicker);
                    //DESTROY HERE
                    if ($(this).data().datepicker) {
                        $(this).datepicker("destroy");
                    }
                    //REBIND HERE
                    if (typeof $(this).data().datepicker == "undefined") {
                        $(this).removeClass("hasDatepicker");
                        if ($(this).attr("data-type")) {
                            if ($(this).attr("data-type") == "date") {
                                $(this).datepicker({
                                    'dateFormat': 'yy-mm-dd'
                                });
                            } else if ($(this).attr("data-type") == "dateTime") {
                                $(this).datetimepicker({
                                    'dateFormat': 'yy-mm-dd'
                                });
                            }
                        }
                    }
                });
                // console.log("STARTING... REBINDING OF COMPUTED DEFAULT VALUE FIELDS LIST THEN");

                //destroy first
                $(".getFields").off("change.repeaterDefaultValueComputed" + table_id);
                $(".getFields").off("keyup.repeaterDefaultValueComputed" + table_id);
                //"startUpDefaultValComputed"
                //makeOnChange(fieldAffected,fieldWithComputation,eventAddressNamespace)
                table.children("tbody").children("tr").each(function(eqi_tr) {
                    $(this).find(".setOBJ").each(function(eqi_setOBJ) {
                        var obj_id = $(this).attr("data-object-id");
                        var this_setOBJFIELD = $(this).find(".getFields_" + obj_id);
                        // console.log("REFRESH")
                        // console.log(this_setOBJFIELD)
                        var this_setOBJFIELD_name = this_setOBJFIELD.eq(0).attr("name");
                        if (this_setOBJFIELD.data("events")) {
                            if (this_setOBJFIELD.data("events").change) {
                                for (var ctr = 0; ctr < this_setOBJFIELD.data("events").change.length; ctr++) {
                                    if (this_setOBJFIELD.data("events").change[ctr].namespace.toLowerCase().indexOf("startup") >= 0) {
                                        return true;
                                    }
                                }
                            }
                        }

                        if (this_setOBJFIELD.data("events")) {
                            if (this_setOBJFIELD.data("events").keyup) {
                                for (var ctr = 0; ctr < this_setOBJFIELD.data("events").keyup.length; ctr++) {
                                    if (this_setOBJFIELD.data("events").keyup[ctr].namespace.toLowerCase().indexOf("startup") >= 0) {
                                        return true;
                                    }
                                }
                            }
                        }

                        if (this_setOBJFIELD.attr("default-type")) { //PA ROW NORMAL lANG
                            if (this_setOBJFIELD.attr("default-type") == "computed") {
                                //REBIND DEFAULT VALUES COMPUTED
                                //console.log("REFRESh");
                                //console.log(this_setOBJFIELD);
                                defaultComputed(obj_id,this_setOBJFIELD,this,"repeaterDefaultValueComputed"+table_id);
                                // console.log( this_setOBJFIELD.parents(".setOBJ").eq(0) )
                            }
                        }
                        //console.log("arrgh")
                        //console.log(this_setOBJFIELD)
                        if (typeof this_setOBJFIELD.attr("event-id-from") != "undefined") { //PACOLUMN FORMULA IS AT OUTER @fieldName[sum]
                            var ids = this_setOBJFIELD.attr("event-id-from").split(",");
                            var idEleWithFormula = "";
                            for(var zz = 0 ; zz < ids.length ; zz++){
                                var idEleWithFormula = $(".getFields_" + ids[zz]);
                                makeOnChange(this_setOBJFIELD, idEleWithFormula, "repeaterDefaultValueComputed" + table_id);
                            }
                            // var idEleWithFormula = $(".getFields_" + this_setOBJFIELD.attr("event-id-from"));
                            // console.log("GEH NGA??")
                            // console.log(this_setOBJFIELD)
                            // makeOnChange(this_setOBJFIELD, idEleWithFormula, "repeaterDefaultValueComputed" + table_id);
                        }
                        
                        //CURRENCY FORMAT
                        if(this_setOBJFIELD.attr("data-input-type") == 'Currency'){
                            var has_change_curr_format = false;
                            var data_events = this_setOBJFIELD.data("events");
                            if(typeof data_events != "undefined"){
                                if(typeof data_events["change"] != "undefined"){
                                    $.each(this_setOBJFIELD.data("events")["change"],function(index, value){
                                        if(value["namespace"] == "currency_format"){
                                            has_change_curr_format = true;
                                            return false;
                                        }
                                    });
                                }
                            }
                            if(has_change_curr_format == false){
                                this_setOBJFIELD.on("change.currency_format",function(){
                                    if($.isNumeric($(this).val())){
                                        var value_number = parseFloat($(this).val());
                                        $(this).val(value_number.currencyFormat());
                                    }else{
                                        var value_nito = $(this).val()
                                        var sanitized_val = value_nito.replace(/[\s,]/g,"");
                                        if($.isNumeric(sanitized_val)){
                                            var value_number = parseFloat(sanitized_val);
                                            $(this).val(value_number.currencyFormat());
                                        }
                                    }
                                });
                            }
                        }


                    });
                });
                table.find(".getFields").change();
            }
                                //TESTING
            function rebindFieldFunctionalityV3(appended_row){
                var select_tbody = $(appended_row).parents("tbody").eq(0);
                // var count_trs = select_tbody.children("tr").length;
                var count_trs = select_tbody.parents("table.form-table").data("added_rows_uid");
                var dis_appended_row = $(appended_row);
                var table_id = dis_appended_row.parents("table.form-table").eq(0).parents(".setOBJ").eq(0).attr("data-object-id");

                //remove class
                dis_appended_row.find(".hasDatepicker").removeClass("hasDatepicker");

                //remove attr's
                dis_appended_row.find("[value]").removeAttr("value");
                
                //fixing ids and names
                dis_appended_row.find("[data-object-id]").each(function(eq_name){//FIX IDS
                    if($(this).attr("rep-data-doi")){ //REPLACING THE GETFIELD UNIQUE CLASS
                        var doi = $(this).attr("rep-data-doi");
                        var getFields = $(this).find("*").filter(function(){
                            var regu_eks = new RegExp("getFields_"+doi,"g");
                            return regu_eks.test($(this).attr("rep-data-class"));
                        });

                        $(this).attr("data-object-id",$(this).attr("rep-data-doi")+"_UID"+count_trs);

                        if(getFields.attr("rep-data-class")){
                            var reg_eks = new RegExp("getFields_[0-9]*","g");
                            var replaced_class = getFields.attr("rep-data-class").replace(reg_eks, "getFields_"+doi+"_UID"+count_trs);
                            getFields.attr("class", replaced_class);
                        }
                    }else{ //REPLACING THE UNIQUE GETFIELD CLASS
                        $(this).attr("rep-data-doi",$(this).attr("data-object-id"));
                        $(this).attr("data-object-id",$(this).attr("data-object-id")+"_UID"+count_trs);
                        var new_doi = $(this).attr("rep-data-doi");
                        var getFields = $(this).find(".getFields_"+new_doi);
                        var reg_eks = new RegExp("getFields_[0-9]*","g");
                        getFields.attr("rep-data-class",getFields.attr("class"));
                        var replaced_class = getFields.attr("class").replace(reg_eks, "getFields_"+new_doi+"_UID"+count_trs);
                        getFields.attr("class", replaced_class);
                    }
                });

                dis_appended_row.find("[id]").each(function(eq_id){//FIX IDS
                    if($(this).attr("rep-data-id")){
                        $(this).attr("id",$(this).attr("rep-data-id")+"_UID"+count_trs);
                    }else{
                        $(this).attr("rep-data-id",$(this).attr("id"));
                        $(this).attr("id",$(this).attr("id")+"_UID"+count_trs);
                    }
                });
                dis_appended_row.find("[name]").each(function(eq_name){//FIX IDS
                    if($(this).attr("rep-original-name")){
                        $(this).attr("name",$(this).attr("rep-original-name")+"_UID"+count_trs);
                    }else{
                        $(this).attr("rep-original-name",$(this).attr("name"));
                        $(this).attr("name",$(this).attr("name")+"_UID"+count_trs);
                    } 
                })

                
                

                //restoring functionality
                {
                    //DATEPICKER
                    dis_appended_row.find('input[data-type="date"]').each(function(eq_d){
                        $(this).datepicker({
                            'dateFormat': 'yy-mm-dd'
                        });
                        if(ThisDate($(this).val()) != "Invalid Date"){
                            $(this).val(ThisDate($(this).val()).formatDate("Y-m-d"));
                        }
                    })
                    //DATETIMEPICKER
                    dis_appended_row.find('input[data-type="dateTime"]').each(function(eq_d){
                        $(this).datetimepicker({
                            dateFormat: 'yy-mm-dd'
                        });
                        if(ThisDate($(this).val()) != "Invalid Date"){
                            $(this).val(ThisDate($(this).val()).formatDate("Y-m-d H:i"));
                        }
                    })
                    //TIME
                    dis_appended_row.find('input[data-type="time"]').each(function(eq_d){
                        $(this).datetimepicker({                   
                            dateFormat: '', 
                            timeFormat: 'HH:mm', 
                            timeOnly: true                                   
                        });
                        if(!$(this).val() && $(this).val().length >= 1){
                            var time_val = ThisDate(ThisDate(new Date()).formatDate("Y-m-d")+" "+$(this).val());

                            if(time_val != "Invalid Date"){
                                $(this).val(time_val.formatDate("H:i"));
                            }
                        }
                        
                    })
                    //CURRENCY
                    dis_appended_row.find(".getFields[data-input-type='Currency']").each(function(){
                        $(this).on("change.currency_format",function(){
                            if($.isNumeric($(this).val())){
                                var value_number = parseFloat($(this).val());
                                $(this).val(value_number.currencyFormat());
                            }else{
                                var value_nito = $(this).val()
                                var sanitized_val = value_nito.replace(/[\s,]/g,"");
                                if($.isNumeric(sanitized_val)){
                                    var value_number = parseFloat(sanitized_val);
                                    $(this).val(value_number.currencyFormat());
                                }
                            }
                        })
                        $(this).change();
                    });
                    //REPEATER ACTION BUTTON DISABLING
                    dis_appended_row.on({
                        "mouseenter":function(e){
                            if(!$(this).find(".repeater-action").hasClass("disable-repeater-action")){
                                $(this).find(".repeater-action").css("display","");
                                $(this).find(".repeater-action").stop(false,false).animate({
                                    "opacity":1
                                },function(){
                                    //TEST
                                })
                            }
                        },
                        "mouseleave":function(e){
                            $(this).find(".repeater-action").stop(false,false).animate({
                                "opacity":0
                            },function(){
                                $(this).css("display","none");
                            })
                        }
                    })
                    {//DISABLING REPEATER ACTION BUTTON BASED OF DISABLED FIELDS
                        var total_field_disabled_in_row = dis_appended_row.find(".getFields:disabled").length;
                        var total_field_in_row = dis_appended_row.find(".getFields").length;
                        if(total_field_disabled_in_row == total_field_in_row){
                            dis_appended_row.find(".repeater-action").addClass("disable-repeater-action");
                        }
                    }
                    //REBIND DEFAILT COMPUTED
                    dis_appended_row.find('.getFields[default-type="computed"][default-formula-value]').each(function(){
                        console.log("ELEMENT REPEATED W FORMULAS "+$(this).attr("name"), $(this));
                        var this_element_setOBJ = $(this).parents(".setOBJ").eq(0);
                        var this_element_field = $(this);
                        var data_obj_id = this_element_setOBJ.attr("data-object-id");

                        defaultComputed(data_obj_id, this_element_field, this_element_setOBJ, "repeaterDefaultValueComputed"+table_id);
                    });
                    //REBIND FIELDS FROM COMPUTED FORMULAS
                    dis_appended_row.find('.getFields[event-id-from]').each(function(eqi){
                        
                        var edoi_from = $(this).attr("event-id-from"); 
                        var element_in_computation = $(this);
                        var splitted_edoi_from = edoi_from.split(",");

                        for(index_oid in splitted_edoi_from){
                            
                            var the_fields = $("[data-object-id='"+splitted_edoi_from[index_oid]+"']").find(".getFields_"+splitted_edoi_from[index_oid]);
                            if(the_fields.attr("default-formula-value")){
                                console.log("ID MAY FORMULA"+splitted_edoi_from[index_oid],the_fields.attr("name"), element_in_computation.attr("name"), "TBL ID::"+table_id)
                                var eventAddressNamespace = "repeaterDefaultValueComputed" + table_id;
                                makeOnChange(element_in_computation, the_fields, eventAddressNamespace);
                            }
                        }
                        
                    })
                    //TRIGGER CHANGES OF NEWLY ADDED ROW
                    dis_appended_row.find('.getFields').filter(function(index, element){
                        var dis_ele = $(element);
                        var dis_ele_ev_data = dis_ele.data("events")
                        if(dis_ele_ev_data){
                            if(dis_ele_ev_data["change"]){
                                if(dis_ele_ev_data["change"].length >= 1){
                                    return true;
                                }
                            }
                        }
                    }).change();
                }
            }

            function evRepeaterRemove(repeaterBtnEle) {
                if (repeaterBtnEle.children(".rep-remove-spec-row").length >= 1) {
                    repeaterBtnEle.children(".rep-remove-spec-row").on({
                        "click": function(e) {
                            e.preventDefault();
                            if ($(this).attr("disabled")) {

                            } else {
                                $(this).closest("tr").children("td").animate({
                                    "height": 0
                                }, function() {
                                    var this_table = $(this).closest(".form-table");
                                    $(this).closest("tr").remove();
                                    this_table.find("tbody").eq(0).children("tr").eq(0).find(".getFields").filter(function(index, dom){ //UNANG ROW LANG ANG NAKA .CHANGE
                                        var dis_ele_dom = $(this)
                                        var ded_data_events = dis_ele_dom.data("events");
                                        if(ded_data_events["change"]){
                                            if(ded_data_events["change"].length >= 1){
                                                return true;
                                            }
                                        }
                                        return false;
                                    }).change();
                                    // refreshRepeaterTable(this_table);
                                    // rebindFieldFunctionalityV2(this_table);
                                });
                            }
                            return false;
                        }
                    });
                }
            }
            function refreshRepeaterTable(tableEle) {
                var field_container = ".setOBJ";
                var table_body = $(tableEle).children("tbody");
                var table_row = table_body.children("tr");
                $(table_row).each(function(eqi_tr_i) {
                    var total_field_disabled_in_row = $(this).find(".getFields:disabled").length;
                    var total_field_in_row = $(this).find(".getFields").length;
                    if (total_field_in_row == total_field_disabled_in_row) {
                        $(this).find(".repeater-action").css("opacity", 0);
                        $(this).find(".repeater-action").addClass("disable-repeater-action");
                        $(".disable-repeater-action").children(".rep-remove-spec-row,.rep-add-spec-row").attr("disabled", true);
                        $(".disable-repeater-action").children(".rep-remove-spec-row,.rep-add-spec-row").prop("disabled", true);
                    }
                    if ($(this).hasClass("original-row")) {
                        //
                    } else {
                        $(this).find(field_container).each(function() {
                            sobj_index_id = $(this).attr("data-object-id");
                            $(this).find(".getFields_" + sobj_index_id).each(function() {

                                if (!$(this).attr("rep-original-id")) {
                                    $(this).attr("rep-original-id", $(this).attr("id"));
                                    $(this).attr("id", $(this).attr("rep-original-id") + "_tr" + eqi_tr_i);
                                } else {
                                    //
                                    $(this).attr("id", $(this).attr("rep-original-id") + "_tr" + eqi_tr_i);
                                }

                                if (!$(this).attr("rep-original-name")) {
                                    $(this).attr("rep-original-name", $(this).attr("name"));
                                    $(this).attr("name", $(this).attr("rep-original-name") + "_tr" + eqi_tr_i);
                                } else {
                                    //
                                    $(this).attr("name", $(this).attr("rep-original-name") + "_tr" + eqi_tr_i);
                                }

                                //MAKE AN INDEX TOO ON FORMULAS
                                // if($(this).attr("default-type")){
                                //    if($(this).attr("default-type") == "computed"){
                                //      var computed_default_value = $(this).attr("default-formula-value");
                                //      var splitted_default_val = computed_default_value.match(/@\(.*?\)|@[a-zA-Z0-9_]*/g);
                                //      if(splitted_default_val != null){
                                //            console.log("FIGURE THIS OUT")
                                //            for(var ctr = 0 ; ctr < splitted_default_val.length ; ctr++){
                                //                  var formula_key_words = new Array("@Department","@Status","@Requestor","@RequestID","@Now","@Today","@TrackNo","@CurrentUser","@StrRight","@StrLeft","@GivenIf");
                                //                  var ele_in_formula = $('[name="'+splitted_default_val[ctr].replace("@","")+'"]');
                                //                  if(ele_in_formula.length >= 1){
                                //                        console.log(ele_in_formula.data("events"));
                                //                        var ele_in_f_val = $.trim(ele_in_formula.val() );
                                //                        if($.isNumeric(ele_in_f_val ) ){
                                //                             computed_default_value = computed_default_value.replace(splitted_default_val[ctr], ele_in_f_val);
                                //                        }else{
                                //                             computed_default_value = computed_default_value.replace(splitted_default_val[ctr], "\""+ele_in_f_val+"\"");
                                //                        }
                                //                  }else{
                                //                         if(formula_key_words.indexOf(splitted_default_val[ctr]) >= 0 ){
                                //                            if(splitted_default_val[ctr] == "@Requestor"){
                                //                                 requestor_ele = "<?php echo $auth['display_name']; ?>";
                                //                                 computed_default_value = computed_default_value.replace(splitted_default_val[ctr],"\""+requestor_ele+"\"" );
                                //                            }else if(splitted_default_val[ctr] == "@RequestID"){
                                //                                 var value_reqID = $("#ID").val();
                                //                                 computed_default_value = computed_default_value.replace(splitted_default_val[ctr], value_reqID);
                                //                            }else if(splitted_default_val[ctr] == "@Department"){
                                //                                 var value_reqID = $("[name='Department_Name']").val();
                                //                                 computed_default_value = computed_default_value.replace(splitted_default_val[ctr], value_reqID);
                                //                            }else if(splitted_default_val[ctr] == "@RowIndex"){

                                //                                 if($(this).parents("tr").length >=1){
                                //                                     var rowIndex_val = $(this).parents("tr").eq(0).index();
                                //                                     computed_default_value = computed_default_value.replace(splitted_default_val[ctr], rowIndex_val);
                                //                                 }
                                //                            }
                                //                            continue;
                                //                          }else{
                                //                            var toBeReplace = splitted_default_val[ctr];
                                //                            var formula_RegExp = new RegExp("("+toBeReplace+"|"+toBeReplace+"_tr[0-9]*)","g");
                                //                            computed_default_value = computed_default_value.replace(formula_RegExp, splitted_default_val[ctr].replace(/_tr[0-9]*/g,"")+"_tr"+eqi_tr_i);
                                //                          }
                                //                  }
                                //            }
                                //      }
                                //      var status_ok = "false";
                                //      try{
                                //         eval(computed_default_value);
                                //         status_ok = "true";
                                //      }catch(eerr){

                                //      }
                                //      if(status_ok== "true"){
                                //         $(this).val(eval(computed_default_value));
                                //      }
                                //    }
                                // }
                            });

                            $(this).find(".pickListButton").each(function() {
                                if (!$(this).attr("original-return-field")) {
                                    $(this).attr("original-return-field", $(this).attr("return-field"));
                                    $(this).attr("return-field", $(this).attr("original-return-field") + "_tr" + eqi_tr_i);
                                } else {
                                    $(this).attr("return-field", $(this).attr("original-return-field") + "_tr" + eqi_tr_i);
                                }
                            });
                        });
                    }
                });
                if (typeof callBack != "undefined") {
                    callBack(tableEle);
                }
            }

            refreshRepeaterTable(tableElement); // this excute at the startup of repeater table ... so that the rows with no fields 
        }



        // {//eyAH NEW VERSION REPEATER TABLE FAST
        //     function evRepeaterAddV2(row_button){
        //         if (row_button.find(".rep-add-spec-row").length >= 1) {
        //             row_button.find(".rep-add-spec-row").eq(0).on("click",function(){
        //                 var tr_element = $(this).parents("tr").eq(0);
        //                 var tr_append_location = tr_element;
        //                 var tr_cloned = tr_element.clone();
        //                 tr_append_location.after(tr_cloned);
        //                 tr_cloned.find(".rep-remove-spec-row").css("display","");
        //             })
        //         }
        //     }
        //     function evRepeaterRemoveV2(row_button){
        //         if (row_button.find(".rep-remove-spec-row").length >= 1) {
        //             row_button.find(".rep-remove-spec-row").eq(0).on("click",function(){
        //                 alert("MAYNUS");
        //             })
        //         }
        //     }
        // }

        if (typeof callBack != "undefined") {
            callBack(tableElement);
        }
    }

    var adjustComponentBelowV2 = {//NOTE: CONSIDER PARENT KEY JSON
        collectedDatas: null,
        collectObjects: function() {
            //collect tables
            var collect_table_containers = [];
            $(".form-table").each(function(eqi_form_table) {
                var setOBJ_container = $(this).parents(".setOBJ").eq(0);
                // setOBJ_container.css("box-shadow","0 0 20px violet");
                var setOBJ_posTop = setOBJ_container.position().top;
                var setOBJ_posLeft = setOBJ_container.position().left;
                var setOBJ_posBottom = setOBJ_container.position().top + setOBJ_container.outerHeight();
                var setOBJ_posRight = setOBJ_container.position().left + setOBJ_container.outerWidth();

                var setOBJ_offsTop = setOBJ_container.offset().top;
                var setOBJ_offsLeft = setOBJ_container.offset().left;
                var setOBJ_offsBottom = setOBJ_container.offset().top + setOBJ_container.outerHeight();
                var setOBJ_offsRight = setOBJ_container.offset().left + setOBJ_container.outerWidth();

                var setOBJ_originWidth = setOBJ_container.outerWidth();
                var setOBJ_originHeight = setOBJ_container.outerHeight();

                collect_table_containers.push({
                    "data_obj_id": setOBJ_container.attr("data-object-id"),
                    "element": setOBJ_container,
                    "element_parent_container": setOBJ_container.parent(),
                    "ele_parent_origin_height": setOBJ_container.parent().outerHeight(),
                    "ele_parent_origin_width": setOBJ_container.parent().outerWidth(),
                    "setOBJ_posTop": setOBJ_posTop,
                    "setOBJ_posLeft": setOBJ_posLeft,
                    "setOBJ_posBottom": setOBJ_posBottom,
                    "setOBJ_posRight": setOBJ_posRight,
                    "setOBJ_offsTop": setOBJ_offsTop,
                    "setOBJ_offsLeft": setOBJ_offsLeft,
                    "setOBJ_offsBottom": setOBJ_offsBottom,
                    "setOBJ_offsRight": setOBJ_offsRight,
                    "setOBJ_originWidth": setOBJ_originWidth,
                    "setOBJ_originHeight": setOBJ_originHeight
                });

            });
            //collect objects below
            var table_sorted_offs_top = sortMyObjectByKey(collect_table_containers, "setOBJ_offsTop");

            for (var ctr = 0; ctr < table_sorted_offs_top.length; ctr++) {
                table_sorted_offs_top[ctr].adjust_this_objs = [];
                var condition_left = table_sorted_offs_top[ctr].setOBJ_posLeft;
                var condition_right = table_sorted_offs_top[ctr].setOBJ_posRight;

                table_sorted_offs_top[ctr].element_parent_container.children(".setOBJ").each(function(eqi_setOBJ) {

                    if (
                            table_sorted_offs_top[ctr].setOBJ_posTop <= $(this).position().top &&
                            (
                                    condition_left <= ($(this).position().left + $(this).outerWidth()) &&
                                    condition_right >= ($(this).position().left)
                                    ) &&
                            table_sorted_offs_top[ctr].element.index() != $(this).index()
                            ) {
                        if (condition_left >= $(this).position().left) { //DITO NA AKO
                            condition_left = $(this).position().left;
                        }
                        if (condition_right <= ($(this).position().left + $(this).outerWidth())) {
                            condition_right = ($(this).position().left + $(this).outerWidth());
                        }
                        var setOBJ_container = $(this);
                        // setOBJ_container.css("box-shadow","0 0 20px green");
                        // alert(213)
                        var setOBJ_posTop = setOBJ_container.position().top;
                        var setOBJ_posLeft = setOBJ_container.position().left;
                        var setOBJ_posBottom = setOBJ_container.position().top + setOBJ_container.outerHeight();
                        var setOBJ_posRight = setOBJ_container.position().left + setOBJ_container.outerWidth();

                        var setOBJ_offsTop = setOBJ_container.offset().top;
                        var setOBJ_offsLeft = setOBJ_container.offset().left;
                        var setOBJ_offsBottom = setOBJ_container.offset().top + setOBJ_container.outerHeight();
                        var setOBJ_offsRight = setOBJ_container.offset().left + setOBJ_container.outerWidth();

                        var setOBJ_originWidth = setOBJ_container.outerWidth();
                        var setOBJ_originHeight = setOBJ_container.outerHeight();

                        table_sorted_offs_top[ctr].adjust_this_objs.push({
                            "data_obj_id": setOBJ_container.attr("data-object-id"),
                            "element": setOBJ_container,
                            "element_parent_container": setOBJ_container.parent(),
                            "ele_parent_origin_height": setOBJ_container.parent().outerHeight(),
                            "ele_parent_origin_width": setOBJ_container.parent().outerWidth(),
                            "setOBJ_posTop": setOBJ_posTop,
                            "setOBJ_posLeft": setOBJ_posLeft,
                            "setOBJ_posBottom": setOBJ_posBottom,
                            "setOBJ_posRight": setOBJ_posRight,
                            "setOBJ_offsTop": setOBJ_offsTop,
                            "setOBJ_offsLeft": setOBJ_offsLeft,
                            "setOBJ_offsBottom": setOBJ_offsBottom,
                            "setOBJ_offsRight": setOBJ_offsRight,
                            "setOBJ_originWidth": setOBJ_originWidth,
                            "setOBJ_originHeight": setOBJ_originHeight
                        });

                    }
                });
            }

            this.collectedDatas = table_sorted_offs_top;
        },
        "adjustElements": function() {
            var this_collected_datas = this.collectedDatas;
            for (var ctr = 0; ctr < this_collected_datas.length; ctr++) {
                //INITIALIZATION OF POS/H/W/SELECTOR
                var select_this_table = this_collected_datas[ctr].element;
                var table_originHeight = this_collected_datas[ctr].setOBJ_originHeight;
                var objs_below_this_table = this_collected_datas[ctr].adjust_this_objs

                //CHANGE CSS STYLE TO VIEW ALL ROWS
                if (select_this_table.css("display") != "none") {
                    select_this_table.css({
                        "display": "inline-table"
                    });
                }
                

                //GETTING THE ADDED HEIGHT FROM THE TABLE
                var added_height = $(select_this_table).outerHeight() - table_originHeight;
                // alert(added_height)

                // this_collected_datas[ctr].element.css({
                //     // "background-color":"rgba(200,0,0,0.5)"
                //     "box-shadow":"0px 0px 10px rgba(200,0,0,0.5)"
                // });
                // $(document).scrollTop(this_collected_datas[ctr].element.offset().top);
                // alert("PARENT THE TABLE")



                //ADJUST BELOW ITS TABLE
                for (var ctr2 = 0; ctr2 < this_collected_datas[ctr].adjust_this_objs.length; ctr2++) {
                    this_collected_datas[ctr].adjust_this_objs[ctr2].element.css({
                        // "background-color":"rgba(0,0,200,0.5)"
                        // "box-shadow":"0px 0px 10px rgba(0,0,200,0.5)",
                        "top": (this_collected_datas[ctr].adjust_this_objs[ctr2].element.position().top + added_height) + "px"
                    });
                    // $(document).scrollTop(this_collected_datas[ctr].adjust_this_objs[ctr2].element.offset().top);
                    // alert("BELOW PARENT")
                }
                //ADJUST THE PARENTS OF THE TABLE
                // this.adjustparents(select_this_table, ".showTabObjectGet, .preview_content", added_height)
                if ($(select_this_table).parents(".showTabObjectGet").length >= 1) {
                    $(select_this_table).parents(".showTabObjectGet").each(function(eqi_parents) {
                        // $(this).css({
                        //     "box-shadow":"0px 0px 10px black"
                        // })
                        var this_showtabget = $(this);
                        var this_showtab_index = this_showtabget.index();
                        var parent_of_parents = this_showtabget.parent();
                        var pops_pos_top = this_showtabget.position().top;
                        var pops_pos_left = this_showtabget.position().left;
                        var pops_pos_bottom = this_showtabget.position().top + this_showtabget.outerHeight();
                        var pops_pos_right = this_showtabget.position().left + this_showtabget.outerWidth();

                        var condition_left = pops_pos_left;
                        var condition_right = pops_pos_right;

                        parent_of_parents.children(".setOBJ").each(function() {
                            var sobjs_right = $(this).position().left + $(this).outerWidth();
                            var sobjs_left = $(this).position().left;
                            if (
                                    pops_pos_top <= $(this).position().top &&
                                    this_showtab_index != $(this).index() &&
                                    (condition_left <= sobjs_right && condition_right >= sobjs_left)
                                    ) {
                                if (condition_left >= $(this).position().left) { //DITO NA AKO
                                    condition_left = $(this).position().left;
                                }
                                if (condition_right <= ($(this).position().left + $(this).outerWidth())) {
                                    condition_right = ($(this).position().left + $(this).outerWidth());
                                }
                                $(this).css({
                                    // "box-shadow":"0px 0px 10px red",
                                    "top": ($(this).position().top + added_height) + "px"
                                });
                            }
                        });

                        $(this).css({
                            "height": ($(this).outerHeight() + added_height) + "px"
                        });
                        $(".preview_content").parent().css({
                            "height": ($(".preview_content").parent().height() + added_height) + "px"
                        });
                    });
                } else {
                    $(".preview_content").parent().css({
                        "height": ($(".preview_content").parent().height() + added_height) + "px"
                    });
                }

            }
        }
    }
    function sortMyObjectByKey(arrayObject, keyNameValToSort) {
        var myArrayOfObj = arrayObject;
        // myArrayOfObj.sort(function (a, b) {
        //     if (a[keyNameValToSort] < b[keyNameValToSort]) {
        //         return -1;
        //     }
        //     else if (a[keyNameValToSort] > b[keyNameValToSort]) {
        //         return 1;
        //     }
        //     return 0;
        // });
        // return myArrayOfObj;
        return myArrayOfObj.sort(function(x, y) {
            return x[keyNameValToSort] - y[keyNameValToSort]
        });
    }
    function fieldExists(FIELDNAME){
        var bool_checker = false;
        try{
            var replaced_str = FIELDNAME.replace(/@/g,"")
            var FN_OBJ = $("[name="+replaced_str+"]");
            if(FN_OBJ.length >= 1){
                bool_checker = true;
            }else{
                bool_checker = false;
            }
        }catch(error){
            console.log("NAG ERROR SA FIELDEXISTS",replaced_str,error)
            bool_checker = false;
        }
        return bool_checker;
    }
    function disableAllTheseDays(date) {

    }
    function sanitizeFormulas(myFormula){
        var programKeywords = ["alert","for\(.*;.*;.*\)"];

    }
</script>